Skip to content

Instantly share code, notes, and snippets.

@djaquels
Created January 17, 2021 02:02
Show Gist options
  • Save djaquels/6d87a8e879e79dbe57899648d51f7d58 to your computer and use it in GitHub Desktop.
Save djaquels/6d87a8e879e79dbe57899648d51f7d58 to your computer and use it in GitHub Desktop.
Solve to the reversed polish notation evaluator engine
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