Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python raise ELEMENTDOESNOTEXTIST stack.exceptions.ELEMENTDOESNOTEXTIST_Python_Python 3.x - Fatal编程技术网

Python raise ELEMENTDOESNOTEXTIST stack.exceptions.ELEMENTDOESNOTEXTIST

Python raise ELEMENTDOESNOTEXTIST stack.exceptions.ELEMENTDOESNOTEXTIST,python,python-3.x,Python,Python 3.x,我的RPN计算器有问题: def计算onp(onp): 从stack.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]:

我的RPN计算器有问题:

def计算onp(onp): 从stack.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
类OnpMissingOperationArgument(OnpException): 通过

OnpMissingNumericArgument类(OnpException): 通过

运行此命令后:

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

怎么了?

您的pop函数调用了名为
len(self.stack)
的函数。但它并不存在。因此,在运行什么之后,尝试将名称
def\uu len\uuuu(self):
更改为
def len(self):

len(self.stack)==0