了解如何在Python中创建堆

发布于 2021-01-29 15:08:49

例如collections.Count.most_common,Python中的函数使用该heapq模块返回文件中最常见单词的计数。

我已经跟踪了该heapq.py文件,但是在理解如何相对于假设的单词创建/更新堆方面遇到了一些麻烦。

因此,我认为对我来说最好的理解方法是弄清楚如何从头开始创建堆。

有人可以提供伪代码来创建表示字数的堆吗?

关注者
0
被浏览
85
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    这是在这里找到的代码的略微修改版本:http : //code.activestate.com/recipes/577086-heap-
    sort/

    def HeapSort(A,T):
        def heapify(A):
            start = (len(A) - 2) / 2
            while start >= 0:
                siftDown(A, start, len(A) - 1)
                start -= 1
    
        def siftDown(A, start, end):
            root = start
            while root * 2 + 1 <= end:
                child = root * 2 + 1
                if child + 1 <= end and T.count(A[child]) < T.count(A[child + 1]):
                    child += 1
                if child <= end and T.count(A[root]) < T.count(A[child]):
                    A[root], A[child] = A[child], A[root]
                    root = child
                else:
                    return
    
        heapify(A)
        end = len(A) - 1
        while end > 0:
            A[end], A[0] = A[0], A[end]
            siftDown(A, 0, end - 1)
            end -= 1
    
    
    if __name__ == '__main__':
        text = "the quick brown fox jumped over the the quick brown quick log log"
        heap = list(set(text.split()))
        print heap
    
        HeapSort(heap,text)
        print heap
    

    输出量

    ['brown', 'log', 'jumped', 'over', 'fox', 'quick', 'the']
    ['jumped', 'fox', 'over', 'brown', 'log', 'the', 'quick']
    

    您可以在此处将该程序可视化 http://goo.gl/2a9Bh



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看