python - 在 Python 中使用堆栈计算中缀表达式 : I cant find my error

标签 python python-3.x stack

在查看此代码 2 天后,我决定寻求帮助。这是我第一次提问,所以请耐心等待。

我的编码经验很少,我的知识就显示的代码而言,尽量保持简单。

对于我正在上的类(class),我必须编写代码以正确执行操作顺序,这是我完成的代码:

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

这会引发 IndexError,因为您不能从空列表中pop,并且无论列表是否为空,您的 return 语句都会运行。也许您正在寻找类似以下 (?) 的内容:

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

关于python - 在 Python 中使用堆栈计算中缀表达式 : I cant find my error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22315468/

相关文章:

python - 在 Pandas 中将列拆分为两个新列

python - 无法导入名称模式

python-3.x - Windows 8.1 上 Python 3.4 的 PyCrypto 找不到 winrandom 模块

python - 在 Python 中对整数进行十六进制化

c - 当输入非常大时,我得到段错误

python - 继承: Are parent objects created each time I call 'super' ?

python - 在 Tensorflow 中计算梯度

python - 查找文本中每个句子的长度

c++ - 堆栈溢出 Visual C++,可能是数组大小?

c - 堆栈中的 fatal error