I am having trouble coming up with a recursive method that can solve fully parenthesized equations..such as ((3+2)/(1+4)). I was able to come up with a recursive solution for solving infix expressions like +*+3421 using recursion, but for something like ((3+2)/(1+4)) I am a little stuck.
def evalPrefix(exp):
it = iter(exp)
return evalPrefixInner(it)
def evalPrefixInner(it):
item = it.next()
if isInt(item):
return int(item)
else:
operand1 = evalPrefixInner(it)
operand2 = evalPrefixInner(it)
return execute(item, operand1, operand2)
Your grammar is:
correct?
So, ignoring error checking, something like…