Created
January 17, 2021 02:02
-
-
Save djaquels/6d87a8e879e79dbe57899648d51f7d58 to your computer and use it in GitHub Desktop.
Solve to the reversed polish notation evaluator engine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def eval_expr(operand,a,b): | |
if operand == '+': | |
return a + b | |
elif operand == '-': | |
return a - b | |
elif operand == '*': | |
return a * b | |
else: | |
return a / b | |
def reversed_polish(expr): | |
list = [] | |
operands = ['+','-','*','/'] | |
for elem in expr: | |
if elem in operands: | |
second = list.pop() | |
first = list.pop() | |
result = eval_expr(elem,first,second) | |
list.append(result) | |
else: | |
list.append(elem) | |
print(list) | |
return list[0] | |
test = [1,2,3,'+',2,'*','-'] | |
assert reversed_polish(test) == -9 ,"Wrong" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment