imashutosh51

Evaluate reverse polish notation

Oct 16th, 2022 (edited)
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.68 KB | None | 0 0
  1. /*
  2. Logic:
  3. push numbers into stack and whenever operators comes pop top two items
  4. and operate on them and push the result.
  5. */
  6. class Solution:
  7.     def evalRPN(self, tokens: List[str]) -> int:
  8.         st=[]
  9.         for i in tokens:
  10.             if i.isdigit() or (i[1:].isdigit() and i[0]=='-'):
  11.                 st.append(int(i))
  12.             else:
  13.                 a=st.pop()
  14.                 b=st.pop()
  15.                 if i=='+':
  16.                     st.append(a+b)
  17.                 elif i=='-':
  18.                     st.append(b-a)
  19.                 elif i=='*':
  20.                     st.append(a*b)
  21.                 else:
  22.                     st.append(int(b/a))
  23.         return st[0]
Advertisement
Add Comment
Please, Sign In to add comment