What would you use the heapq Python module for in real life?

前端 未结 3 1111
栀梦
栀梦 2021-02-02 16:59

After reading Guido\'s Sorting a million 32-bit integers in 2MB of RAM using Python, I discovered the heapq module, but the concept is pretty abstract to me.

<
3条回答
  •  南方客
    南方客 (楼主)
    2021-02-02 17:32

    Comparing it to a self-balancing binary tree, a heap doesn't seem to gain you much if you just look at complexity:

    • Insertion: O(logN) for both
    • Remove max element: O(logN) for both
    • Build structure from an array of elements O(N) for heap, O(N log N) for binary tree.

    But whereas a binary tree tends to need each node pointing to its children for efficiency, a heap stores its data packed tightly into an array. This allows you to store much more data in a fixed amount of memory.

    So for the cases when you only need insertion and max-removal, a heap is perfect and can often use half as much memory as a self-balancing binary tree (and much easier to implement if you have to). The standard use-case is a priority queue.

提交回复
热议问题