【发布时间】:2019-01-04 05:57:49
【问题描述】:
考虑 dequeue=[2, 3, 4, None, None, None, 1]。它是循环的,假设 1 是 dequeue 的前面,4 是 dequeue 的后面,敲木头,我们应该将这些索引存储在变量 front 和 back 下,它们的值分别为 6 和 2。
如何打印前后索引之间的值,即 [1, 2, 3, 4]。更好的是,更具体地说,我希望找到一种方法来制作一个更具体地看起来像 [1, 2, 3, 4] 的字符串。我的代码如下,但我不相信它是时间效率的,而且,在我的代码的较大块中,我不确定这种方法是否有效。
def str(self):
if self.size==0: #my first thoughts are to simply catch an empty dequeue
return "[ ]"
elif self.size==1: #same for a dequeue of only one object.
string = "[ "+str(self.__contents[0])+" ]"
return string
else:
string="[ "
index=self.front
while (index%self.capacity) != self.back:
string = string + str(self.contents[index]) + ", "
index+=1
string=string+str(self.__contents[self.back]) + " ]"
return string
其中 self.size=非空条目的数量,self.capacity=数组中的单元格总数,self.contents 表示数组的内容,self.front 和 self.back 表示数组的索引dequeue 的前后。
【问题讨论】:
标签: python list deque circular-list arraydeque