在Python中使用堆栈计算中缀表达式:我找不到我的错误
在看了这段代码两天后,我决定寻求一些帮助。这是我第一次问问题,所以请容忍我 我的编码经验很少,我的知识也很少,只要代码显示,尽量保持简单 对于我正在学习的一个类,我必须编写代码以正确执行操作顺序这是我完成的代码:在Python中使用堆栈计算中缀表达式:我找不到我的错误,python,python-3.x,stack,Python,Python 3.x,Stack,在看了这段代码两天后,我决定寻求一些帮助。这是我第一次问问题,所以请容忍我 我的编码经验很少,我的知识也很少,只要代码显示,尽量保持简单 对于我正在学习的一个类,我必须编写代码以正确执行操作顺序这是我完成的代码: import operator class stack: def __init__(self): self._stack = [] def __len__(self): return len(self._stack) def
import operator
class stack:
def __init__(self):
self._stack = []
def __len__(self):
return len(self._stack)
def is_empty(self):
return len(self._stack) == 0
def push(self, e):
self._stack.append(e)
def top(self):
if self.is_empty():
print ('stack is empty')
return self._stack[-1]
def pop(self):
if self.is_empty():
print ('stack is empty')
return
return self._stack.pop()
def apply(a,b,c):
ops2 = {"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv }
op_char = c
op_func = ops2[op_char]
result = op_func(float(a), float(b))
return result
user = '6 - 5 ( 5 - 3 ) * (4 + 2 )'
#user = input("Enter an expression: ")
print(user)
exp = user.split()
nums = '1234567890'
ops = ['*', '/', '+', '-']
par = ['(', ')']
num = stack()
op = stack()
for each in exp:
print(each)
if each in nums:
num.push(each)
if each == par[0]:
op.push(each)
if each in ops:
if each == ops[2] or ops[3]:
op.push(each)
if each == ops[0] or ops[1]:
while op.top() == (ops[2] or ops[3]) and len(op) > 0 and len(num) >= 2:
ans = apply(num.pop(),num.pop(),op.pop())
num.push(ans)
op.push(each)
if each == par[1]:
while op.top() != "(":
ans = apply(num.pop(),num.pop(),op.pop()) # this line is poping the empty stack
num.push(ans)
op.pop()
while op.is_empty() != True:
ans = apply(num.pop(),num.pop(),op.pop())
num.push(ans)
print(ans)
或者我是这么想的。。。
当我运行这个程序时,我从if each==par[1]
循环中得到一个stack is empty错误,我不知道为什么。我使用的表达式应该等于-6.0
,非常感谢您的帮助
编辑:更改代码后,我处于类似的情况,并假设我在推送或弹出某个位置时出错。在再次浏览代码之后,我仍然找不到错误。再次感谢您的帮助。恐怕此代码还存在其他问题(在修复以下问题后您会发现),但您在问题中提到的问题来自您的
pop
方法:
def pop(self):
if self.is_empty():
print ('stack is empty') # still proceeds to the next line
return self._stack.pop() # won't work if self._stack is empty
这会引发索引器错误,因为您无法从空列表中pop
,并且无论列表是否为空,都将运行return语句。也许你想要的是如下(?):
@当然是用户3404267。我希望有帮助。我刚刚看到你又做了一次编辑。一般来说,最好在新问题中进一步提问,而不是编辑现有问题,因为编辑问题通常不会引起太多注意。此外,这将使您有机会包括遇到的特定错误。(顺便说一句,欢迎来到SO!)谢谢你提供的信息,我不知道该怎么办。我只是想说我明白了
def pop(self):
if self.is_empty():
print ('stack is empty')
return # now you need to deal with the returned None value
return self._stack.pop() # only if not empty