1

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.

  • how about `eval()` Be careful though if the equations are from user input this could be a security issue, because harmful code could get run this way... – Heiner Früh Jun 07 '19 at 15:43

4 Answers4

3

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
rassar
  • 5,412
  • 3
  • 25
  • 41
0

Try

ecuation=("95502+45806-85773-659740")
answer = eval(ecuation)
print(answer)
Vitor Falcão
  • 1,007
  • 1
  • 7
  • 18
0

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
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

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.

manny
  • 338
  • 1
  • 11