postfix = list(map(str, input().split())) # 後序運算式stack = [] # 數字堆疊
for i in postfix:if i.isdigit():stack.append(int(i))else:b = stack.pop(-1) # 先彈出第二個操作數a = stack.pop(-1) # 再彈出第一個操作數if i == '+':stack.append(a + b)elif i == '-':stack.append(a - b)elif i == '*':stack.append(a * b)elif i == '/':stack.append(int(a / b)) # 確保整數除法
ans = stack.pop()print(ans)空列表報錯line 9, in a = stack.pop(-1) # 再彈出第一個操作數 IndexError: pop from empty list
但我太傻找不出來求大大幫幫忙 ouo
運算元為 32 位元有號整數=>有可能有負數。
對於Python,"-1". isdigit()會是false
避免方法:把數字條件判斷加上len(i)>1
postfix = list(map(str, input().split())) # 後序運算式stack = [] # 數字堆疊
for i in postfix:if i.isdigit():stack.append(int(i))else:b = stack.pop(-1) # 先彈出第二個操作數a = stack.pop(-1) # 再彈出第一個操作數if i == '+':stack.append(a + b)elif i == '-':stack.append(a - b)elif i == '*':stack.append(a * b)elif i == '/':stack.append(int(a / b)) # 確保整數除法
ans = stack.pop()print(ans)空列表報錯line 9, in a = stack.pop(-1) # 再彈出第一個操作數 IndexError: pop from empty list
但我太傻找不出來求大大幫幫忙 ouo
題目的數字有可能是負數,例如 -1
、-2
這種
isdigit
不會將他們視為是數字,因為字串內的負號 -
不是數字
一個簡單的解決辦法是建一個表,裡面放運算子 operators = ["+", "-", "*", "/"]
判斷是否是數字時,只需要檢查 i in operators
就可以了,不在裡面的都當成數字看待