我正尝试在Python中建立一个反转波兰语计算器,而且就我而言。它似乎工作,直到我尝试运行PRT,此时我从文本文件中获取最后一个数字,而不是从先前计算中附加到堆栈的结果。 Python不是我的正常语言,所以我对你即将看到的内容表示歉意。在Python中反转波兰语计算器
def is_number(ln):
try:
int(ln)
return True
except ValueError:
return False
def main():
stack = []
# Open file
infile = open('math.txt', 'r')
line = infile.readline()
while line != '':
if is_number(line):
line = int(line)
stack.append(line)
if line in ['ADD', 'SUB', 'MUL', 'DIV']:
if line=='ADD': result = stack.pop() + stack.pop()
if line=='SUB': result = stack.pop() - stack.pop()
if line=='MUL': result = stack.pop() * stack.pop()
if line=='DIV': result = stack.pop()/stack.pop()
print(result)
stack.append(result)
if line=='PRT': print(stack.pop())
if line=='STOP': exit()
line = infile.readline()
# Close file
infile.close()
# Call main function
main()
math.txt:
1
2
3
4
5
6
ADD
PRT
我猜也许问题是与换行符或readline的做,但我就是不使用Python写正常,所以我我不确定。
你可以发布你的math.txt。 –
一旦你修复了你的代码,我就让你[这个要点](https://gist.github.com/spectras/dabae78e0e94a58793b8)带有更多pythonic版本的你做的,所以你可以比较。可能不完美,但利用python的强大代码更清晰。需要python3。 – spectras
@BarunSharma我添加了我的math.txt文件 – skwills