提升ElementDoesNotExist stack.exceptions.ElementDoesNotExist

时间:2017-03-23 08:40:00

标签: python python-3.x

我的RPN计算器出现问题:

def calculate_onp(onp):     来自stack.stack import Stack

OPERATORS = ['+', '-', '*', '/']
s = Stack()

lista = onp.split(" ")

index = None

for i in range(1, len(onp)):
    index = i - 1
    if lista[index] in OPERATORS:
        if lista[index] == OPERATORS[0]:
            num1 = s.pop()
            num2 = s.pop()
            wyn = int(num1) + int(num2)
            s.push(wyn)

        elif lista[index] == OPERATORS[1]:
            num1 = s.pop()
            num2 = s.pop()
            wyn = int(num1) - int(num2)
            s.push(wyn)

        elif lista[index] == OPERATORS[2]:
            num1 = s.pop()
            num2 = s.pop()
            wyn = int(num1) * int(num2)
            s.push(wyn)

        elif lista[index] == OPERATORS[3]:
            num1 = s.pop()
            num2 = s.pop()
            wyn = int(num1) / int(num2)
            s.push(wyn)

        else:
            return 'ERROR'

else:
    s.push(lista[index])

return int(s.pop())

我为此添加了一个堆栈实现:

from stack.exceptions import ElementDoesNotExist

class Stack(object):

    def __init__(self):
        self.stack = []

    def __len__(self):
        return len(self.stack)

    def push(self, s):
        return self.stack.append(s)

    def pop(self):
        if len(self.stack) == 0:
            raise ElementDoesNotExist
        else:
            return self.stack.pop()

    def show_list(self):
        print(self.stack)

例外:

堆栈的

class ElementDoesNotExist(Exception):
    pass

表示rpn:

class OnpException(Exception):
    pass

class OnpMissingOperationArgument(OnpException):         通

class OnpMissingNumericArgument(OnpException):         通

运行之后:

        File "/home/maciek/PycharmProjects/Calc/stack/stack.py", line 16, in pop
    raise ElementDoesNotExist
stack.exceptions.ElementDoesNotExist

怎么了?

1 个答案:

答案 0 :(得分:0)

你的pop函数调用了一个名为len(self.stack)的函数。但它不存在。请尝试将名称def __len__(self):更改为def len(self):