I am learning Python from interactivepython.org. On this site, they have the code for evaluating postfix expressions.. but I would like to see how it would be done for prefix expressions as well. Here is the code:
def postfixEval(postfixExpr):
operandStack = Stack()
tokenList = postfixExpr.split()
for token in tokenList:
if token in "0123456789":
operandStack.push(int(token))
else:
operand2 = operandStack.pop()
operand1 = operandStack.pop()
result = doMath(token,operand1,operand2)
operandStack.push(result)
return operandStack.pop()
def doMath(op, op1, op2):
if op == "*":
return op1 * op2
elif op == "/":
return op1 / op2
elif op == "+":
return op1 + op2
else:
return op1 - op2
print(postfixEval('7 8 + 3 2 + /'))
If I understand this lesson correctly, would I just change the operand ordering?
No, the operands come in the same order. The difference is that you have to take the operation before the operands instead of afterward. This is complicated by the fact that you likely have to make recursive calls to evaluate the operands: if an operand begins with an operation, you recur.