I've been trying to solve this 'equation' using recursion (without regex), but for some reason it keeps resetting the def par(string)
back after action(calc)
has finished its first loop, instead of continuing from where it (i) was before the first par function started (the i local variable resets to 40 after the calc loop).
my code prints out
1
1
1
if I do
print par(equation)
it prints out
1
there is no real reason to print inside the function, but I was wondering if you guys could help me out here, im using Python 2.7
here is my code:
equation = "[[[3+4] + [5*6]] + [5/7] / [[3+2] + [4/2]] * [2-1]]"
equation = equation.replace(" ", "")
def action(calc):
x = int(calc[0])
y = int(calc[2])
if calc[1] == "+":
result = x+y
elif calc[1] == "-":
result = x-y
elif calc[1] == "*":
result = x*y
else:
result = x/y
return result
def par(string):
for i in range(len(string)-1, 0, -1):
if string[i] == "]":
result = par(string[:i])
elif string[i] != "[":
calc = string[i-2:i+1]
result = action(calc)
return result
else:
return result
par(equation)