python 中的最小堆

发布于 2024-07-16 05:02:24 字数 113 浏览 5 评论 0原文

我想通过定义自定义比较函数将一组对象存储在最小堆中。 我看到有一个 heapq 模块作为 python 发行版的一部分可用。 有没有办法在此模块中使用自定义比较器? 如果没有,其他人是否构建了自定义最小堆?

I'd like to store a set of objects in a min heap by defining a custom comparison function. I see there is a heapq module available as part of the python distribution. Is there a way to use a custom comparator with this module? If not, has someone else built a custom min heap?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

友欢 2024-07-23 05:02:24

有两个选项(除了 Devin Jeanpierre 的建议):

  1. 在使用堆之前装饰您的数据。 这相当于排序的 key= 选项。 例如,如果您(出于某种原因)想根据正弦值堆积数字列表:

    data = [ # 数字列表 ] 
      堆 = [(math.sin(x), x) 对于数据中的 x] 
      heapq.heapify(堆) 
      # 获取最小元素 
      项目 = heappop(堆)[1] 
      
  2. heapq 模块是用纯 python 实现的。 您只需将其复制到工作目录并更改相关位即可。 快速浏览一下,您必须修改 siftdown() 和 siftup(),如果需要的话还可能需要修改 nlargest 和 nsmallest。

Two options (aside from Devin Jeanpierre's suggestion):

  1. Decorate your data before using the heap. This is the equivalent of the key= option to sorting. e.g. if you (for some reason) wanted to heapify a list of numbers according to their sine:

    data = [ # list of numbers ]
    heap = [(math.sin(x), x) for x in data]
    heapq.heapify(heap)
    # get the min element
    item = heappop(heap)[1]
    
  2. The heapq module is implemented in pure python. You could just copy it to your working directory and change the relevant bits. From a quick look, you would have to modify siftdown() and siftup(), and possibly nlargest and nsmallest if you need them.

○闲身 2024-07-23 05:02:24

是的,有办法。 定义一个实现自定义比较器的包装类,并使用这些比较器的列表而不是实际对象的列表。 这是在仍然使用 heapq 模块时最好的,因为它没有像排序函数/方法那样提供 key= 或 cmp= 参数。

def gen_wrapper(cmp):
    class Wrapper(object):
        def __init__(self, value): self.value = value
        def __cmp__(self, obj): return cmp(self.value, obj.value)
    return Wrapper

Yes, there is a way. Define a wrapping class that implements your custom comparator, and use a list of those instead of a list of your actual objects. That's about the best there is while still using the heapq module, since it provides no key= or cmp= arguments like the sorting functions/methods do.

def gen_wrapper(cmp):
    class Wrapper(object):
        def __init__(self, value): self.value = value
        def __cmp__(self, obj): return cmp(self.value, obj.value)
    return Wrapper
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文