【问题标题】:IndexError from calling an Integer调用 Integer 导致的 IndexError
【发布时间】:2012-04-11 16:43:49
【问题描述】:

我正在使用堆栈类为程序添加前缀。但是,每当我调用整数时,push() 方法都会引发 IndexError,即使我有一个异常处理程序并且我引用的是整数本身,而不是列表。

stack.py:

class stack():
    def __init__(self,n):
        self.n = n
        self.top = -1
        self.stack = [""] * n

    #...

    def push(self,c):
        try:
            print(self.top)
            self.top += 1
            self.stack[self.top] = c
        except IndexError:
            print("Stack is full.")

pip.py:

def toPrefix(input):
    instack = stack(15)
    prefix = ""

    for i in range(0,len(input)):
        for c in range(0,len(input[i])):
            if(input[i][c].isalpha()):
                instack.push(input[i][c])

错误:

Traceback (most recent call last):
  File "<string>", line 247, in run_nodebug
  File "P:\Scripts\Python\ascl-pip.py", line 42, in <module>
    toPrefix(infix)
  File "P:\Scripts\Python\ascl-pip.py", line 37, in toPrefix
    instack.push(input[i][c])
  File "P:\Scripts\Python\stack.py", line 36, in push
    print(self.top)
IndexError: list assignment index out of range

【问题讨论】:

  • 请始终包含您收到的错误消息的完整回溯。
  • 而且你不需要实现堆栈。标准 Python 列表具有 append()pop() 方法。
  • @SvenMarnach 这是一个需要我编写自己的堆栈类的类。
  • 您对toPrefix的意见是什么
  • 输入是三个字符串的列表。 “abcde”、“abcde”和“abcdef”,所以应该是一个IndexError,但它没有被异常处理程序捕获,并且IndexError不是来自输入或堆栈变量.

标签: python python-3.x stack-overflow


【解决方案1】:

您的回溯不一致。它声称这条线

print(self.top)

IndexError的原因,但print()永远不会引发这样的错误。

发生这种情况的唯一方法是您使用的旧版本的模块仍然加载在解释器实例中。重新启动您的解释器。

如果你真的需要实现自己的堆栈类,你可以用这样的愚蠢的东西:

class Stack(list):
    push = list.append

此堆栈的大小不受限制。

【讨论】:

  • push = list.append 现在这只是试图击败系统 :) 我认为标记作业的人不会对此印象深刻
  • @KshitijMehta:我的态度是荒谬的任务应该得到荒谬的解决方案。如果您应该在 C 中实现堆栈,那很好。但是,Python 中的堆栈将不可避免地基于列表,因此您应该在堆栈实现之上编写堆栈实现。我建议的实现只是强调了这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-30
  • 1970-01-01
  • 1970-01-01
  • 2023-01-30
  • 2019-02-23
  • 1970-01-01
  • 2022-11-18
相关资源
最近更新 更多