Postfix Notation Evaluator Function
Suppose you are given the following string to parse out as a mathematical operation in postfix notation
3 4 + 5 6 + *
to parse out
That is in normal infix notation (3 + 4) * (5 + 6)
. Therefore the answer for both should be 77
To do this you should create a stack of last in first out and evaluate is the current token an operation or a number literal. Came up with this which uses the eval
function to run the operation and place the intermediate result back onto the stack
Solution
def reverse_polish_evaluator(expression):
current = []
for token in expression.split():
if token.isdigit():
current.append(float(token))
continue
current.append(eval(f'{current.pop()} {token} {current.pop()}'))
return current.pop()
if __name__ == '__main__':
print(reverse_polish_evaluator("3 4 + 5 6 + *"))