我有这个代码可以正常工作,但我无法弄清楚如何正确格式化。
from Stack import*
def main():
file=input("Enter the name of the file containing postfix expressions: ")
file=open(file, 'r')
stack=Stack()
operators=["/", "*", "-", "+"]
for line in file:
try:
print("Expression: " ,line)
expression=line.split()
for i in expression:
if i not in operators:
stack.push(i)
if i == "/":
x=int(stack.pop())
y=int(stack.pop())
stack.push(y/x)
if i == "*":
x=int(stack.pop())
y=int(stack.pop())
stack.push(x*y)
if i == "+":
x=int(stack.pop())
y=int(stack.pop())
stack.push(x+y)
if i == "-":
x=int(stack.pop())
y=int(stack.pop())
stack.push(y-x)
if stack.size() > 1:
print("Error: ",line,"is an invalid postfix expression")
else:
print("Answer: " ,stack.pop())
except IndexError:
print("Error: ",line,"is an invalid postfix expression.")
except ValueError:
print("Error: ",line,"is an invalid postfix expression.")
main()
但输出结果看起来像这样: 我认为它看起来不错是非常重要的,但我希望它能够实现。
Enter the name of the file containing postfix expressions: expressions.txt
Expression: 5 4 3 + 2 * -
Answer: -9
Expression: 8 5 *
Answer: 40
Expression: 20 5 /
Answer: 4.0
Expression: 3 8 6 + *
Answer: 42
Expression: 3 4 + 9 - 12 +
Answer: 10
Expression: 9 3 2 1 + + /
Answer: 1.5
Expression: 3 + 4
Error: 3 + 4
is an invalid postfix expression.
Expression: * 3 4 5 + *
Error: * 3 4 5 + *
is an invalid postfix expression.
Expression: 4 9 1 3 + -
Error: 4 9 1 3 + -
is an invalid postfix expression
Expression: h 3 +
Error: h 3 +
is an invalid postfix expression.
这里发生了什么?
答案 0 :(得分:2)
在你的文件的字符串末尾可能会有一个\ n换行符。尝试使用python的str.strip()函数剥离它。
答案 1 :(得分:0)
这样的打印元素会为您提供听起来不需要的额外空间。
>>> print('a', 'b')
a b
所以,你想要改变
print("Error: ",line,"is an invalid postfix expression.")
到
print("Error:", line, "is an invalid postfix expression.")
同样,改变
print("Answer: " ,stack.pop())
到
print("Answer:", stack.pop())
注意:我已将逗号移到更标准的位置,但这种差异没有任何影响。
More information here, including how to use the end
parameter.您可能也会受益于字符串格式化操作,有关可以找到的信息here。