Understanding how to create a heap in Python

前端 未结 4 2043
生来不讨喜
生来不讨喜 2020-12-23 14:32

The collections.Count.most_common function in Python uses the heapq module to return the count of the most common word in a file, for instance.

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-23 15:16

    Your confusion may come from the fact that the Python module heapq does not define a heap as a data type (a class) with its own methods (e.g. as in a deque or a list). It instead provides functions that you can run on a Python list.

    It's best to think of heapq as a module providing a set of algorithms (methods) to interpret lists as heaps and manipulate them accordingly. Note that it's common to represent heaps internally as arrays (as an abstract data structure), and Python already has lists serving that purpose, so it makes sense for heapq to just provide methods to manipulate lists as heaps.

    Let's see this with an example. Starting with a simple Python list:

    >>> my_list = [2, -1, 4, 10, 0, -20]
    

    To create a heap with heapq from my_list we just need to call heapify which simply re-arranges the elements of the list to form a min-heap:

    >>> import heapq
    >>> # NOTE: This returns NoneType:
    >>> heapq.heapify(my_list)
    

    Note that you can still access the list underlying the heap, since all heapify has done is change the value referenced by my_list:

    >>> my_list
    [-20, -1, 2, 10, 0, 4]
    

    Popping elements from the heap held by my_list:

    >>> [heapq.heappop(my_list) for x in range(len(my_list))]
    [-20, -1, 0, 2, 4, 10]
    

提交回复
热议问题