我正嘗試在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