One way of handling this might be with regular expressions. You can use re.sub
with a lambda, and specified to only sub one time, in a while loop to continually replace subexpressions with their results until no operators are found.
This does not respect order of operations.
import re
e = '5+5-4+55-5*6/2'
while re.search(r'[+\-*/]', e):
e = re.sub(r'(\d+)([*/+\-])(\d+)',
lambda x: f"{int(x.groups()[0]) + int(x.groups()[2])}" if (op := x.groups()[1]) == '+' else \
f"{int(x.groups()[0]) - int(x.groups()[2])}" if op == '-' else \
f"{int(x.groups()[0]) * int(x.groups()[2])}" if op == '*' else \
f"{int(x.groups()[0]) / int(x.groups()[2])}",
e, 1)
Result is 168.0
.
It is possible to modify this slightly to look for only multiplication and vision first, then to look for addition and subtraction.
import re
e = '5+5-4+55-5*6/2'
while re.search(r'[/*]', e):
e = re.sub(r'(\d+)([/*])(\d+)',
lambda x: f"{int(x.groups()[0]) * int(x.groups()[2])}" if x.groups()[1] == '*' else \
f"{int(x.groups()[0]) / int(x.groups()[2])}",
e, 1)
while re.search(r'[+\-]', e):
e = re.sub(r'(\d+)([+\-])(\d+)',
lambda x: f"{int(x.groups()[0]) + int(x.groups()[2])}" if x.groups()[1] == '+' else \
f"{int(x.groups()[0]) - int(x.groups()[2])}",
e, 1)
Result: e
is now 46.0
.