[PY3]——heap模組 和 堆排序

Jelly_lyj發表於2017-03-18

heapify( )

heapify()函式用於將一個序列轉化為初始化堆

nums=[16,7,3,20,17,8,-1]
print('nums:',nums)
show_tree(nums)

nums: [16, 7, 3, 20, 17, 8, -1]

                 16                 
        7                 3         
    20       17       8        -1   
------------------------------------

heapq.heapify(nums)
print('nums:',nums)
show_tree(nums)

nums: [-1, 7, 3, 20, 17, 8, 16]

                 -1                 
        7                 3         
    20       17       8        16   
------------------------------------

 

heappush( )

heappush()是實現將元素插入到堆的操作
heappush()操作前一定要先將序列初始化成堆!heappush是對於"堆"的操作!不然是沒有意義

nums=[16,7,3,20,17,8,-1]
print(nums)
show_tree(nums)

       [16, 7, 3, 20, 17, 8, -1]

                   16                 
          7                 3         
      20       17       8        -1   
  ------------------------------------

heapq.heapify(nums)
print('初始化成堆:',nums)  
show_tree(nums)

    初始化成堆: [-1, 7, 3, 20, 17, 8, 16]

                     -1                 
            7                 3         
        20       17       8        16   
    ------------------------------------
for i in random.sample(range(1,8),2):
    print("本次push:",i)
    heapq.heappush(nums,i)
    print(nums)
    show_tree(nums)
    
    本次push: 5
    [-1, 5, 3, 7, 17, 8, 16, 20]

                     -1                 
            5                 3         
        7        17       8        16   
     20 
    ------------------------------------

    本次push: 7
    [-1, 5, 3, 7, 17, 8, 16, 20, 7]

                     -1                 
            5                 3         
        7        17       8        16   
     20  7  
    ------------------------------------

 

heappop( )

heappop()是實現將元素刪除出堆的操作
同樣的操作前一定要先將序列初始化成堆,否則也沒什麼意義

nums=[16,7,3,20,17,8,-1]
print(nums)
show_tree(nums)

          [16, 7, 3, 20, 17, 8, -1]

                       16                 
              7                 3         
          20       17       8        -1   
      ------------------------------------

heapq.heapify(nums)
print('初始化成堆:',nums)
show_tree(nums)

        初始化成堆: [-1, 7, 3, 20, 17, 8, 16]

                         -1                 
                7                 3         
            20       17       8        16   
        ------------------------------------
for i in range(0,2):
    print("本次pop:",heapq.heappop(nums))
    print(nums)
    show_tree(nums)

        本次pop: -1
        [3, 7, 8, 20, 17, 16]

                         3                  
                7                 8         
            20       17       16   
        ------------------------------------

        本次pop: 3
        [7, 16, 8, 20, 17]

                         7                  
                16                8         
            20       17   
        ------------------------------------

 

nlargest( )/nsmallest( )

sorted(iterable, key=key, reverse=True)[:n]

  • nlargest(n,iterable) 求序列iterable中的TopN | nsmallest(n,iterable) 求序列iterable中的BtmN
import heapq
nums=[16,7,3,20,17,8,-1]
print(heapq.nlargest(3,nums))
print(heapq.nsmallest(3,nums))

[20, 17, 16]
[-1, 3, 7]
  • nlargest(n, iterable, key=lambda) | nsmallest(n, iterable, key=lambda) key接受關鍵字引數,用於更復雜的資料結構中
def print_price(dirt):
    for i in dirt:
        for x,y in i.items():
            if x=='price':
                print(x,y)

portfolio = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {'name': 'FB', 'shares': 200, 'price': 21.09},
    {'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}
]

cheap=heapq.nsmallest(3,portfolio,key=lambda x:x['price'])
expensive=heapq.nlargest(3,portfolio,key=lambda y:y['price'])
print_price(cheap)
print_price(expensive)

price 16.35
price 21.09
price 31.75

price 543.22
price 115.65
price 91.1

 

關於heap和heap sort

對於上面的nums=[16,7,3,20,17,8,-1]序列,圖解了:

構造堆的操作(點選檢視)

push堆的操作(點選檢視)

pop堆的操作(點選檢視)

 

參考文章

詳解Python中heapq模組的用法(包括show_tree())

詳解堆排序

淺談演算法和資料結構: 五 優先順序佇列與堆排序

 

相關文章