【发布时间】:2011-09-16 21:58:12
【问题描述】:
我有一个创建循环数组类的项目,我将使用的语言是 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 中测试它们时,我得到一个索引错误......我不知道为什么。这不是唯一的问题,这只是我陷入困境并需要帮助前进的地方。
我在这里发帖是因为我需要帮助并想学习,而不是因为我很懒并且没有尝试研究我的问题。已经谢谢了!
【问题讨论】:
-
a=[]; a[1]=3会产生同样的错误。您不能写入不存在的索引。你想做什么,这是一个圆形(固定大小)缓冲区吗? -
@yi_H 是的,这是一个编写执行上述操作的固定循环缓冲区的项目。我已经修复了索引问题,现在我调用的每个函数都没有定义错误,所以我猜我的语法有问题。
-
小提示:当你在索引中加或减一个时,你不必验证索引是否(分别)等于容量或
标签: python class circular-buffer