So, i've been writing a calculator and a problem that faced me is that i can't add more than two numbers at a time.
i decided that since i'm using split then adding the items in the list should be the best solution
it does read the number in index 0 as an int indeed, but it doesn't for the rest
i tried to loop over the items in the list in order to add them.
that failed so i tried to use the sum() function in order to sum the items in the new list and then add that to the number in index 0, still doesn't work
my code:
def calc(x):
if ' ' in x:
i = x.split(' ')
a = sum(i[1:])
print(int(i[0]) int(a))
the error that pops up here is:
line 5, in calc
a = sum(i[1:])
TypeError: unsupported operand type(s) for : 'int' and 'str'
CodePudding user response:
Splitting a string yields a list of strings. You can't sum
strings.
But you can turn your list of strings into ints and sum it.
>>> [int(x) for x in '1 2 3 4'.split(' ')]
[1, 2, 3, 4]
>>> sum(int(x) for x in '1 2 3 4'.split(' '))
10
CodePudding user response:
The variable i will be a (potentially empty) list of strings. So you're trying to sum strings.
Assuming your function is only meant to handle addition of integers then:
def calc(s):
return sum(map(int, s.split(' ')))
print(calc('19 17'))
Output:
36
Additional:
Let's extend this function to support addition, subtraction, multiplication and division. No error/sanity checking so exceptions may arise if the string format is not exactly as expected.
from operator import add, sub, mul, truediv
import re
opmap = {' ': add, '-': sub, '*': mul, '/': truediv}
def calc(s):
x, o, y = re.search(r'(\d )\s*([ -/*])\s*(\d )', s).groups()
return opmap[o](int(x), int(y))
print(calc('19 * 17'))
Output:
323