Answer to Question #277335 in Python for AYUSH PATIL

Question #277335

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


1
Expert's answer
2021-12-09T01:23:39-0500
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])




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS