我不断收到 IndexError: list index out of range, return self.data[-1] # the last element in the list; 我想我知道是什么原因造成的,但我不知道如何解决它
这是我使用的堆栈类:
class Stack:
# LIFO Stack implementation using a Python list as underlying storage.
def __init__(self):
self.data =[]
def __len__(self):
return len(self.data)
def is_empty(self):
return len(self.data)==0
def push(self, e):
self.data.append(e)
def top(self):
return self.data[-1]
def pop(self):
return self.data.pop()
以及我制作的相应代码:
def operatorpriority(x):
if x == "+" or x == "-":
return 1
elif x == "*" or x == "/":
return 2
else:
return 3
return 0
def polishnotation(A):
# Converts Infix to Prefix Notation
stack = Stack()
stack.push(')')
A = A + '('
output = ""
for i in range(len(A)-1, -1, -1):
print(i)
if A[i].isnumeric() == True:
output+=A[i]
elif A[i] == ")":
stack.push(A[i])
elif A[i] == "-" or A[i] == "+" or A[i] == "*" or A[i] == "/" or A[i] == "^":
if A[i] == "^":
while operatorpriority(A[i]) <= operatorpriority(stack.top()):
output+=stack.pop()
else:
while operatorpriority(A[i]) < operatorpriority(stack.top()):
output+=stack.pop()
stack.push(A[i])
elif A[i] == "(":
while stack.is_empty()== False:
if stack.top() != "(":
output+=stack.pop()
stack.pop()
while stack.is_empty()== False:
output+=stack.pop()
print(output)
InfixInput = input("Input infix notation: ")
polishnotation(InfixInput)
样本输入:
(a+b)*(cd)
预期输出:
*+ab-cd