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.
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
Try
ecuation=("95502+45806-85773-659740")
answer = eval(ecuation)
print(answer)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.