【问题标题】:Printing the nonempty portion of a circular dequeue打印循环出队的非空部分
【发布时间】: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


    【解决方案1】:

    你想使用内置的deque吗?如果是这样,它支持标准迭代,使列表理解非常 Python:

    '[{}]'.format(', '.join(x for x in my_deque if x is not None)
    

    如果它不是内置的deque,为什么不为您的类型添加迭代支持以允许上述方法(可能还有许多其他方法)。

    【讨论】:

    • 一般来说,我不喜欢使用内置功能。尽管它有很大帮助,但我觉得它有点欺骗了我应该从中学习的项目的一些目的。不过,无论如何,谢谢你的回答。实际上我今天早上早些时候解决了我的问题,将来我希望利用内置的双端队列!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多