Skip to content

Instantly share code, notes, and snippets.

@DreamVB
Created September 22, 2019 18:09
Show Gist options
  • Select an option

  • Save DreamVB/976e07e1d0ac8edb169f06fe18960e27 to your computer and use it in GitHub Desktop.

Select an option

Save DreamVB/976e07e1d0ac8edb169f06fe18960e27 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Python Version
# Reverse Polish notation demo
# Basic calulator for RPN expression only + / * - is supported.
# Allows ints and floats.
import math
stack = []
def IsNuber(s):
is_num = True
for n in s:
if str.isdigit(n) or n == ".":
is_num = True
else:
is_num = False
break
return is_num
def rpn(expression):
parts = expression.split(" ")
for s in parts:
value = s.strip()
if len(value):
if IsNuber(value):
stack.append(value)
else:
if value == "+":
# Pop of the values from the stack
a = stack.pop()
b = stack.pop()
res = float(a) + float(b)
stack.append(res)
if value == "-":
# Pop of the values from the stack
a = stack.pop()
b = stack.pop()
res = float(b) - float(a)
stack.append(res)
if value == "*":
# Pop of the values from the stack
a = stack.pop()
b = stack.pop()
res = float(a) * float(b)
stack.append(res)
if value == "/":
# Pop of the values from the stack
a = stack.pop()
b = stack.pop()
res = float(b) / float(a)
stack.append(res)
return float(stack.pop())
# Infix == (4 * (12 + 3) / 2 * (5 + 5) - (100 * 2))
expr = "4 12 3 + * 2 / 5 5 + * 100 2 * - 2 /"
print(rpn(expr))
# float test pi
expr = "22 7 /"
print(rpn(expr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment