[python] heapq๋ชจ๋“ˆ

Minhee kangยท2021๋…„ 6์›” 30์ผ
0

Python

๋ชฉ๋ก ๋ณด๊ธฐ
3/25

๐Ÿ“’ ๊ธฐ๋ณธ์ ์ธ ์‚ฌ์šฉ๋ฒ•

#min heap(์ตœ์†Œ ํž™)์—์„œ ๊ฐ€์žฅ ์ž‘์€๊ฐ’์€ ์–ธ์ œ๋‚˜ ์ธ๋ฑ์Šค 0, ์ฆ‰, ์ด์ง„ ํŠธ๋ฆฌ์˜ ๋ฃจํŠธ์— ์œ„์น˜
#      1  ---> root
#    /   \
#   3     5
#  / \   /
# 4   8 7

#heapq ๋ชจ๋“ˆ์€ ์ด์ง„ ํŠธ๋ฆฌ(binary tree) ๊ธฐ๋ฐ˜์˜ ์ตœ์†Œ ํž™(min heap) ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์ œ๊ณต
#heqpq๋ชจ๋“ˆ์€ ํŒŒ์ด์ฌ์˜ ๋ณดํ†ต ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งˆ์น˜ ์ตœ์†Œ ํž™์ฒ˜๋Ÿผ ๋‹ค๋ฃฐ ์ˆ˜ ์žˆ๋„๋ก ๋„์™€์คŒ. ๋ณ„๊ฐœ์˜ ์ž๋ฃŒ๊ตฌ์กฐ X
#ํŒŒ์ด์ฌ์—์„œ๋Š” heapq ๋ชจ๋“ˆ์„ ํ†ตํ•ด์„œ ์›์†Œ๋ฅผ ์ถ”๊ฐ€ํ•˜๊ฑฐ๋‚˜ ์‚ญ์ œํ•œ ๋ฆฌ์ŠคํŠธ๊ฐ€ ๊ทธ๋ƒฅ ์ตœ์†Œ ํž™์ด ๋จ.

import heapq

a = [] #ํŒŒ์ด์ฌ์˜ ์ผ๋ฐ˜์ ์ธ ๋ฆฌ์ŠคํŠธ ์„ ์–ธ

heapq.heappush(a, 6)   #๋ฆฌ์ŠคํŠธ๋ฅผ ์ธ์ž๋กœ ๋„˜๊ฒจ ์›์†Œ๋ฅผ ์ถ”๊ฐ€
heapq.heappush(a, 1)
heapq.heappush(a, 4)
heapq.heappush(a, 5)

print(a)  #[1, 5, 4, 6]

print(heapq.heappop(a)) #๋ฆฌ์ŠคํŠธ๋ฅผ ์ธ์ž๋กœ ๋„˜๊ฒจ ์›์†Œ๋ฅผ ์‚ญ์ œ. 1 ์ถœ๋ ฅ ๋จ.
print(heapq.heappop(a)) #4 ์ถœ๋ ฅ
print(a[0])  #์ œ๊ฑฐํ•˜์ง€ ์•Š๊ณ  ์ตœ์†Œ๊ฐ’ 5์ถœ๋ ฅ, ๊ทธ ์ „์— heapq๋ชจ๋“ˆ์˜ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์ด 0์ธ๋ฑ์Šค์— ์˜ค๋„๋ก ์ •๋ ฌ๋˜์–ด ์žˆ์Œ.
print(a)  #[5, 6]

#----------------------------------------------------#
#heapq.heappop() ์ฃผ์˜ํ•  ์ 
#์ œ์ผ ์•ž์— ์žˆ๋Š” ์›์†Œ ์ œ๊ฑฐํ•˜๊ณ  ํž™ ๊ตฌ์กฐ๋กœ ๋งŒ๋“ฌ
c = [6, 8, 4, 1] 

print(c) #[6, 8, 4, 1]
print(heapq.heappop(c))  #6
print(c)  #[1, 8, 4]
print(heapq.heappop(c))   #1
print(c)  #[4, 8]
print(heapq.heappop(c))  #4
print(c)   #[8]
print(heapq.heappop(c))  #8
#----------------------------------------------------#

#ํž™ ๊ตฌ์กฐ๋กœ ์žฌ๋ฐฐ์น˜
b = [4, 1, 7, 3, 8, 5]
heapq.heapify(b)   #ํž™ ๊ตฌ์กฐ์— ๋งž๊ฒŒ b๊ฐ€ ์žฌ๋ฐฐ์น˜ ๋จ
print(b)

๐Ÿ“’ ์‘์šฉ

#์ตœ๋Œ€ ํž™ -------------------------------------------

import heapq

nums = [4, 1, 7, 3, 8, 5]
max_heap = []

for num in nums:
    heapq.heappush(max_heap, (-num, num))

while max_heap:
    print(heapq.heappop(max_heap)[1])   # ์ถœ๋ ฅ
                                        # 8
                                        # 7
                                        # 5
                                        # 4
                                        # 3
                                        # 1  
                                        
# K๋ฒˆ์งธ ์ตœ์†Œ๊ฐ’ ------------------------------------------

def k_min_val(list, k):

    heapq.heapify(list)  #์ตœ์†Œ ํž™ ๊ตฌ์กฐ๋กœ ์žฌ๋ฐฐ์น˜
    
    for _ in range(k):   #heappop์„ k๋ฒˆ ๋ฐ˜๋ณต
        min = heapq.heappop(list)

    return min

a = [8,3,7,5,6]
print(k_min_val(a, 3))   #6์ถœ๋ ฅ


#ํž™ ์ •๋ ฌ ------------------------------------------------

def sort_heap(list):

    nums = []
    for i in list:   # ์ด ๋ถ€๋ถ„ heapq.heapify()๋กœ ๋Œ€์ฒด ๊ฐ€๋Šฅ
        heapq.heappush(nums, i)      
    
    sorted_nums = []
    while nums:
        sorted_nums.append(heapq.heappop(nums))

    return sorted_nums

b = [8,3,7,5,6]
print(sort_heap(b))   #[3, 5, 6, 7, 8]

0๊ฐœ์˜ ๋Œ“๊ธ€