Reputation: 47
I have this code
ecuation=("95502+45806-85773-659740")
answer = sum(int(x) for x in ecuation if x.isdigit())
print(answer)
Which prints this as answer
105
This is not correct, the idea is to get the ecuation from a web page (I already have that part working) and solve it.
note: The ecuation will always change but it will always be adding and substracting numbers.
Upvotes: 1
Views: 106
Reputation: 338
What you're doing is this calculation:
9+5+5+0+2+4+5+8+0+6+8+5+7+7+3+6+5+9+7+4+0=105
What you want to do is break apart the string and add/subtract those numbers. This can be shortcut by using eval() (more here), as suggested by Vitor, or with ast.literal_eval (more here), as suggested by rassar.
Upvotes: 0
Reputation: 195438
Using re
:
import re
ecuation= "95502+45806-85773-659740"
s = sum(int(g) for g in re.findall(r'((?:\+|-)?\d+)', ecuation))
print(s)
Prints:
-604205
Upvotes: 0
Reputation: 5660
You can try using the eval
function:
>>> ecuation=("95502+45806-85773-659740")
>>> eval(ecuation)
-604205
However, you need to be very careful while using this. A safer way is:
>>> import ast
>>> ast.literal_eval(ecuation)
-604205
Upvotes: 3
Reputation: 1049
Try
ecuation=("95502+45806-85773-659740")
answer = eval(ecuation)
print(answer)
Upvotes: 0