覆盖Python 3 maxheap

时间:2018-11-18 21:06:57

标签: python-3.x

我正在尝试在Python 3中覆盖“最大堆”。 没用我已经重写了 gt 比较器。

它应该有一种简单的方法可以在Python中实现,对吧?

前2个项目的输出为'i', 'coding' 但是,期望项目是“我,爱”

这根本没有道理。不确定为什么Python heapq模块如此令人困惑。

# ["i", "love", "leetcode", "i", "love", "coding"]

from collections import defaultdict
from heapq import heappush, _heappop_max, _heapify_max

class node(object):
    def __init__(self, cnt, word):
        self.cnt = cnt
        self.word = word

    def __lt__(self, other):
        return self.cnt < other.cnt

    def __gt__(self, other):
        return self.cnt > other.cnt

    def __eq__(self, other):
        return self.cnt ==  other.cnt

class Solution(object):
    def topKFrequent(self, words, k):
        """
        :type words: List[str]
        :type k: int
        :rtype: List[str]
        """
        heaped_words = []
        _heapify_max(heaped_words)
        counts = defaultdict(lambda: 0)
        results = []
        for i in words:
            counts[i] += 1
        for word, count in counts.items():
            heappush(heaped_words, node(count, word))

        while heaped_words:
            item = _heappop_max(heaped_words)
            if item:
                results.append(item.word)

        return results

1 个答案:

答案 0 :(得分:0)

您不需要为_heapmax_...使用API​​函数来实现最大堆。相反,您可以通过更改每个节点上的符号(即node(-count, word))来简单地交换将项目推入堆的优先级。

然后,您的最大堆数很容易变为:

from collections import Counter

def topKFrequent(words, k):
        """
        :type words: List[str]
        :type k: int
        :rtype: List[str]
        """
        counts = Counter(words)
        heaped_words = []
        for word, count in counts.items():
            heappush(heaped_words, node(-count, word))
        return [heappop(heaped_words).word for _ in range(k)]


lst = ["i", "love", "leetcode", "i", "love", "coding"]
print(topKFrequent(lst, 2))
# ['i', 'love']

请注意,如果 k 几乎与输入列表的大小一样大,则可以在函数内提供分支指令,只需在列表上调用sorted即可,返回排序列表;这将比多次推送和弹出更加有效。