Created
October 25, 2015 17:22
-
-
Save ejcer/774dcbeac5f588d21021 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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