Understanding how to create a heap in Python

前端 未结 4 2019
生来不讨喜
生来不讨喜 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:09

    Here's another variation based on Sedgewick

    The heap is represented internally in an array where if a node is at k, it's children are at 2*k and 2*k + 1. The first element of the array is not used, to make the math more convenient.

    To add a new element to the heap, you append it to the end of the array and then call swim repeatedly until the new element finds its place in the heap.

    To delete the root, you swap it with the last element in the array, delete it and then call sink until the swapped element finds its place.

    swim(k):
      while k > 1 and less(k/2, k):
        exch(k, k/2)
        k = k/2
    
    sink(k):
      while 2*k <= N:
        j = 2*k
        if j < N and less(j, j+1):
          j++
        if not less(k, j):
          break
        exch(k, j)
        k = j
    

    Here's a visualization of heap insert, inserting the first 15 letters of the alphabet: [a-o]

    heap insert visualization

提交回复
热议问题