【发布时间】:2019-09-24 01:25:32
【问题描述】:
我需要在 python 中构建一个循环缓冲区作为具有高效搜索的双端队列(不是 O(n) el in deque,而是 O(1),如 set())
from collections import deque
deque = deque(maxlen=10) # in my case maxlen=1000
for i in range(20):
deque.append(i)
deque
Out[1]: deque([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
10 in deque # but it takes O(n), I need O(1)
Out[1]: True
我想我需要维护一个单独的字典进行查找,并在双端队列已满时从中删除,但不明白如何。我不需要从 deque 的中间删除,只需像 deque 那样删除 append 并快速查找。
【问题讨论】:
-
请用查找示例更新您的问题,即使效率低下。
-
大声思考:单独的
dict有两个问题: 1. 如果要附加很多东西,如何使dict匹配deque的内容。 2. 如果双端队列中有重复项,如何将内容存储在dict或set中。 -
1.不知道 2. 如果传入的项目在
dict中,我不会添加到deque,这就是我将使用独特元素跟踪deque的方式 -
好吧,基本上你想要
deque的构造函数(即maxlen)加上append(),再加上in(即__contains__(),所以这看起来很简单。也许你可以使用您自己的具有deque作为成员的类以及我概述的方法来更新您的问题。
标签: python performance dictionary data-structures deque