a python program using list to implement reverse polish notation calculator. In reverse polish notation, mathematical expressions are written with the operator following its operands. For example, 3 + 4 becomes 3 4 +. Order of operations is entirely based on the ordering of the operators and operands. To write 3 + (4 ∗ 2), we would write 3 4 2 ∗ + in RPN. The expressions are evaluated from left to right. Evaluate the expression and display the result. [CO1] [L2]
For a sample workout as given below:
Input:
5 // length of list
["2","1","+","3","*"] //actual list
Output:
9
Test Cases are
case=1
input=9
5 1 2 / 4 * + 3 -
output=4
case=2
input=5
2 1 + 3 *
output=9
n = int(input('input: '))
lst = input().split()
stack = []
for i in lst:
if i == '+':
stack[-2] = stack[-2] + stack[-1]
stack.pop()
elif i == '-':
stack[-2] = stack[-2] - stack[-1]
stack.pop()
elif i == '*':
stack[-2] = stack[-2] * stack[-1]
stack.pop()
elif i == '/':
stack[-2] = stack[-2] / stack[-1]
stack.pop()
else:
stack.append(int(i))
print('output:', stack[0])
Comments
Leave a comment