【问题标题】:How to maintain deque with quick lookup?如何通过快速查找维护双端队列?
【发布时间】: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. 如果双端队列中有重复项,如何将内容存储在dictset 中。
  • 1.不知道 2. 如果传入的项目在dict 中,我不会添加到deque,这就是我将使用独特元素跟踪deque 的方式
  • 好吧,基本上你想要deque的构造函数(即maxlen)加上append(),再加上in(即__contains__(),所以这看起来很简单。也许你可以使用您自己的具有deque 作为成员的类以及我概述的方法来更新您的问题。

标签: python performance dictionary data-structures deque


【解决方案1】:

正如你所说,我猜你必须创建一个数据结构,使用deque 来插入/删除,set 来查找 O(1),如下所示:

from collections import deque

class CircularBuffer:
    def __init__(self, capacity):
        self.queue = deque()
        self.capacity = capacity
        self.value_set = set()

    def add(self, value):
        if self.contains(value):
            return
        if len(self.queue) >= self.capacity:
            self.value_set.remove(self.queue.popleft())
        self.queue.append(value)
        self.value_set.add(value)

    def contains(self, value):
        return value in self.value_set

测试和输出

cb = CircularBuffer(10)

for i in range(20):
    cb.add(i)

print(cb.queue)
print(cb.contains(10))

# deque([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
# True

实现一个简单的LRU Cachedict+double linked list也是类似的思路。
希望对您有所帮助,如果您还有其他问题,请发表评论。 :)

【讨论】:

  • 好的,我希望 OP 会先尝试一下。但很好的答案。您提供了简单的代码,以及示例用法和输出! +1
  • 它是操作系统中的一个工业过程,对吧?到目前为止,我只能做到这一点。 :) @quamrana
  • 请注意:您还没有对deque 中没有重复的要求做任何事情。
  • 修复它。感谢您提及它,我之前没有阅读评论。 @quamrana
  • 我已经考虑过了,但是你必须得到弹出的元素,然后从集合中移除,所以这里不需要 max_len。 @丹丹
猜你喜欢
  • 2023-03-28
  • 2017-05-06
  • 2020-04-19
  • 2018-12-02
  • 2018-07-02
  • 1970-01-01
  • 2015-08-18
  • 1970-01-01
  • 2017-04-16
相关资源
最近更新 更多