Skip to content

Instantly share code, notes, and snippets.

@myrkvi
Created May 26, 2015 09:10
Show Gist options
  • Save myrkvi/5e7df37c7b692c21cf81 to your computer and use it in GitHub Desktop.
Save myrkvi/5e7df37c7b692c21cf81 to your computer and use it in GitHub Desktop.
A terrible way of creating a RPN calculator in Python 2
# -*- coding: utf-8 -*-
from sys import argv
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def fOrI(s):
def isfloat(x):
try:
a = float(x)
except ValueError:
return False
else:
return True
def isint(x):
try:
a = float(x)
b = int(a)
except ValueError:
return False
else:
return a == b
if isint(s):
return int(s)
elif isfloat(s):
return float(s)
def solveRpn(math):
s = Stack()
for i in math:
if i == "+":
a = s.pop()
b = s.pop()
s.push( a+b )
elif i == "-":
a = s.pop()
b = s.pop()
s.push( a-b )
elif i == "*":
a = s.pop()
b = s.pop()
s.push( a*b )
elif i == "/":
a = s.pop()
b = s.pop()
s.push( a/b )
else:
s.push( fOrI(i) )
print( s.pop() )
solveRpn(argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment