Skip to content

Instantly share code, notes, and snippets.

@ejcer
Created October 25, 2015 17:22
Show Gist options
  • Save ejcer/774dcbeac5f588d21021 to your computer and use it in GitHub Desktop.
Save ejcer/774dcbeac5f588d21021 to your computer and use it in GitHub Desktop.
def main():
PF1 = "124*+3-22+-3/2/3*"
PF2 = "65-4*54/7*+9-9-"
global tos
tos = -1
def push(s, elem):
global tos
tos = 1+tos
s[tos] = elem
def pop(s):
global tos
val = s[tos]
tos = tos - 1
return val
def Calculator(expression):
stack = [0] * len(expression)
#use array of size expression
def add(a, b):
return (float(a) + float(b))
def sub(a, b):
return (float(b) - float(a))
def mult(a, b):
return (float(a) * float(b))
def divide(a, b):
return (float(b) / float(a))
for x in expression:
#if mult pop twice off stack
push(stack, x)
if x == '*':
pop(stack)
push(stack, mult(pop(stack), pop(stack)))
elif x == '/':
pop(stack)
push(stack, divide(pop(stack), pop(stack)))
elif x == '+':
pop(stack)
push(stack, add(pop(stack), pop(stack)))
elif x == '-':
pop(stack)
push(stack, sub(pop(stack), pop(stack)))
print(pop(stack))
Calculator(PF1)
Calculator(PF2)
Calculator("64-1-2-3-4-")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment