如果我将一个角色推入 Stack 并查看它,它会给我不同的角色,即使在推送后没有进行任何交互。
相关代码的类如下所示:
class Stack:
def __init__(self):
self.data = []
self.top = -1
self.max = 10
def push(self, input):
if self.isFull():
print(f"Push({input}) : Stack is full")
else:
self.top += 1
self.data.append(input)
def pop(self):
if self.isEmpty():
print("Pop : Stack is empty")
else:
temp = self.data[self.top]
self.top -= 1
return temp
def peek(self):
if self.isEmpty():
print("Peek : Stack is empty")
else:
return self.data[self.top]
def printStack(self):
if self.isEmpty():
print("Print : Stack is empty")
else:
print("Stack : ", end="")
for i in range(0,self.top+1):
print(self.data[i], end=" ")
print()
infixToPostfix() 函数如下所示:
def infixToPostfix(input):
stack = Stack()
result = []
for i in input:
print(f"i = '{i}'")
if type(i) == float:
result.append(i)
elif i == '(':
stack.push(i)
elif i == ')':
while stack.isEmpty() == False and stack.peek() != '(':
result.append(stack.pop())
stack.pop()
else:
while stack.isEmpty() == False and stack.peek() != '(' and priority(i) <= priority(stack.peek()):
result.append(stack.pop())
stack.push(i)
print(f"stack.peek() = '{stack.peek()}'")
print(f"result = {result}")
stack.printStack()
print()
while stack.isEmpty() == False:
result.append(stack.pop())
return result
输入本身通过以下代码给出:
input = input("expression : ")
postfix = infixToPostfix(stringToList(input))
print(f"postfix : {postfix}")
我三重检查了其他代码(包括 stringToList() )是否正常工作。
当给定
(10+2*1.5)*3
作为输入时,代码输出如下:
i = '('
result = []
Stack : (
i = '10.0'
result = [10.0]
Stack : (
i = '+'
stack.peek() = '+'
result = [10.0]
Stack : ( +
i = '2.0'
result = [10.0, 2.0]
Stack : ( +
i = '*'
stack.peek() = '*'
result = [10.0, 2.0]
Stack : ( + *
i = '1.5'
result = [10.0, 2.0, 1.5]
Stack : ( + *
i = ')'
result = [10.0, 2.0, 1.5, '*', '+']
Print : Stack is empty
i = '*'
stack.peek() = '('
result = [10.0, 2.0, 1.5, '*', '+']
Stack : (
i = '3.0'
result = [10.0, 2.0, 1.5, '*', '+', 3.0]
Stack : (
postfix : [10.0, 2.0, 1.5, '*', '+', 3.0, '(']
从第 8 次迭代可以看出,'*' 变成了 '(' 没有具体原因。 预期输出为:
i = '3.0'
result = [10.0, 2.0, 1.5, '*', '+', 3.0]
Stack : *
因此制作后缀:
[10.0, 2.0, 1.5, '*', '+', 3.0, '*']
我已将 print(i) 移到 printStack() 方法的正上方,但我得到了相同的输出。
我已经尝试了所有我能接触到的 python 解释器,但总是得到相同的结果,所以我认为这不是本地环境问题。