1

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)
Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
Ronkol
  • 11
  • 1
  • You'll want to read up on parsing and context-free grammars. – chepner Sep 27 '18 at 20:44
  • 1
    "I've been trying to solve this 'equation' using recursion" Your solution doesn't use recursion. – mypetlion Sep 27 '18 at 20:45
  • if this is a division, then you have an extra bracket somewhere at the beginning. and why do you have this as a string? last thing why you have the square brackets instead of parenthesis? – Herc01 Sep 27 '18 at 20:56
  • @Herc01 Its not a 'real' question, just something someone gave me and told me to solve without regex. like calculating the sum of nested lists. – Ronkol Sep 27 '18 at 21:09
  • A return will force the for loop to break, whereas print won't. https://stackoverflow.com/questions/750136/how-is-returning-the-output-of-a-function-different-from-printing-it . What is the desired output? A fun way to do this is: `eval(equation.replace('[','(').replace(']',')'))`... `Out[44]: 37.10204081632653` – cosmic_inquiry Sep 28 '18 at 05:06
  • @cosmic_inquiry Thanks alot, helped me a ton. – Ronkol Sep 28 '18 at 10:10

0 Answers0