I need some help to complete this code i am doing for my programming class. I a working with stacks and need to create a program that evaluates postfix notations. I have input 'expressions.txt' file that has all the postfix notations i need to evaluate. My program evaluates 6 out of 10 notations, i need help to do the rest 4.
Attached along is the text file that contains postfix notations. I am attaching Stacks.py and ListNode.py files with changed file format to .txt so that i can upload them.
I am also pasting my driver.py program here. Any input is highly appreciated. Thanks in advance.
from Stack import *
def postFix(expression):
myStack= Stack()
tokenList= expression.split()
for token in tokenList:
if token.isdigit():
myStack.push(int(token))
elif token == '+':
if not myStack.is_empty():
x = myStack.pop()
else:
print("\nERROR: ", expression, "is an invalid postfix expression.")
break
if not myStack.is_empty():
y = myStack.pop()
else:
print("\nERROR: ", expression, "is an invalid postfix expression.")
break
summ = x + y
myStack.push(summ)
elif token == '-':
if not myStack.is_empty():
x = myStack.pop()
else:
print("\nERROR: ", expression, "is an invalid postfix expression.")
break
if not myStack.is_empty():
y = myStack.pop()
else:
print("\nERROR: ", expression, "is an invalid postfix expression.")
break
subs = y - x
myStack.push(subs)
elif token == '*':
if not myStack.is_empty():
x = myStack.pop()
else:
print("\nERROR: ", expression, "is an invalid postfix expression.")
break
if not myStack.is_empty():
y = myStack.pop()
else:
print("\nERROR: ", expression, "is an invalid postfix expression.")
break
prod = x * y
myStack.push(prod)
elif token == '/':
if not myStack.is_empty():
x = myStack.pop()
else:
print("\nERROR: ", expression, "is an invalid postfix expression.")
break
if not myStack.is_empty():
y = myStack.pop()
else:
print("\nERROR: ", expression, "is an invalid postfix expression.")
break
divi = y / x
myStack.push(divi)
else:
print("\nERROR: ", expression, "is an invalid postfix expression.")
return myStack.pop()
#Main program
FileName = input("Enter the name of the file containing postfix expressions: ")
user = open(FileName , 'r')
for each in user:
line= each.strip()
print ("\n","Expression: ",line, "\n", "Answer: ", postFix(line))
user.close()
Attached File(s)
-
expressions.txt (87bytes)
Number of downloads: 167 -
ListNode.txt (687bytes)
Number of downloads: 116 -
Stack.txt (998bytes)
Number of downloads: 155

New Topic/Question
Reply


MultiQuote



|