0

我有一个创建循环数组类的项目,我将使用的语言是 python。我是 python 类的新手,但在阅读了一些网页和书籍章节后,我想我对它们的工作原理有所了解。但是我需要帮助,所以我想我会来 SO 的优秀老师那里 :)

我们的类必须能够实现几个操作;在前面插入,在后面插入,在索引处插入,从前面删除,从后面删除,从索引中删除。

我已经开始编码,但遇到了一些问题,我不能 100% 确定我的语法是否正确。

这是我到目前为止所拥有的:

class circular:

    def __init__(self):
        self.store = []
        self.capacity = len(self.store)
        self.size = 0
        self.startIndex = 0
        self.endIndex = 0

    def decrementIndex(self):
        index = index - 1
        if index < 0:
            self.store = self.store + self.capacity

    def incrementIndex(self):
        index = index + 1
        if index == self.capacity:
            index = index - self.capacity

    def addToBack(self, value):
        self.store[self.endIndex] = value
        self.endIndex = incrementIndex(self.endIndex)
        self.size += 1

    def addToFront(self, value):
        if self.size == 0:
            addToBack(self, value)
        else:
            self.startIndex = decrementIndex(self.startIndex)
            self.store[self.startIndex] = value
            self.size += 1

我在那里停下来开始测试一些功能,主要是 addTofront 和 addToback。在使用 c = circular() 和 c.addToBack(2) 在 IDLE 中测试它们时,我得到一个索引错误......我不知道为什么。这不是唯一的问题,这只是我陷入困境并需要帮助前进的地方。

我在这里发帖是因为我需要帮助并想学习,而不是因为我懒惰并且没有尝试研究我的问题。已经谢谢了!

4

1 回答 1

1

__init__你设置

self.store = []

addToBack你做

self.store[self.endIndex] = value

如果这是对循环数组的第一个操作,并且您将2其作为传递value,那么它将变成

[][0] = 2

问题应该很明显——一个空列表没有 的索引0,它根本没有索引。

您需要以不同的方式将项目添加到列表中。

我不会确切地告诉你如何解决这个问题,因为这是你家庭作业的一部分。

于 2011-09-16T22:06:16.780 回答