在Python中使用Stacks评估中缀表达式:我无法找到我的错误

时间:2014-03-11 02:46:33

标签: python python-3.x stack

看了这段代码2天后,我决定寻求帮助。这是我第一次问一个问题所以请耐心等待。

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

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

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]循环的空错误,我无法弄清楚为什么。我使用的表达式假设等于-6.0,任何帮助都会受到赞赏。

编辑:更改代码后,我处于类似的情况,并假设我在推送或弹出某个地方时出错。再次遍历代码后,我仍然无法找到错误。再次,任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:3)

我担心此代码存在其他问题(一旦您修复了以下内容,您会发现),但您在问题中提到的问题来自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