데이터를 정렬된 상태로 저장하기 위해서 사용하는 파이썬의 내장 모듈
heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2]
예를 들어, 아래 그림은 위 공식을 만족시키는 간단한 min heap의 구조를 보여주고 있습니다.
1 ---> root
/ \
3 5
/ \ /
4 8 7
from heapq import heappush, heappop
heap = []
heappush(heap,4)
heappush(heap,1)
heappush(heap,7)
heappush(heap,3)
heappush(heap,8)
heappush(heap,5)
print(heap)
▶
[1, 3, 5, 4, 8, 7]
heappush vs append
heappush
는 추가해줄 때마다 heap 정렬이 자동으로 진행
append
는 맨 뒤에 원소 추가
heap = [1, 3, 5, 4, 8, 7]
heap.append(0)
print(heap)
▶
[1, 3, 5, 4, 8, 7, 0]
heap = [1, 3, 5, 4, 8, 7]
heappush(heap,0)
print(heap)
▶
[0, 3, 1, 4, 8, 7, 5]
print(heappop(heap))
▶
1
print(heap)
▶
[3, 4, 5, 7, 8]
print(heappop(heap))
▶
3
print(heap)
▶
[4, 7, 5, 8]
print(heappop(heap))
▶
4
print(heap)
▶
[5, 7, 8]
heap = []
heappush(heap,4)
heappush(heap,1)
heappush(heap,7)
heappush(heap,3)
heappush(heap,8)
heappush(heap,5)
print(heap)
▶
[1, 3, 5, 4, 8, 7]
print(heap[0])
▶
1
heappush(heap, 1)
print(heap[0])
▶
1
print(heap)
▶
[1, 3, 1, 4, 8, 7, 5]
a = heapify(a) => a=None
from heapq import heapify
heap = [4,1,7,3,8,5]
heapify(heap)
print(heap)
▶
[1, 3, 5, 4, 8, 7]
nums = [4,1,7,3,8,5]
heap = nums[:]
heapify(heap)
print(heap)
▶
[1, 3, 5, 4, 8, 7]
print(nums)
▶
[4, 1, 7, 3, 8, 5]
from heapq import heappush, heappop
nums = [4,1,7,3,8,5]
heap = []
for num in nums :
heappush(heap,(-num,num))
while heap :
print(heap)
print(heappop(heap)[1])
▶
[(-8, 8), (-7, 7), (-5, 5), (-1, 1), (-3, 3), (-4, 4)]
8
[(-7, 7), (-4, 4), (-5, 5), (-1, 1), (-3, 3)]
7
[(-5, 5), (-4, 4), (-3, 3), (-1, 1)]
5
[(-4, 4), (-1, 1), (-3, 3)]
4
[(-3, 3), (-1, 1)]
3
[(-1, 1)]
1
from heapq import heappush, heappop, heapify
def nth_smallest(nums, n):
heap = []
for num in nums :
heappush(heap, num)
# heap = nums[:]
# heapify(nums) heapify로 한번에 가능
nth_min = None
for _ in range(n):
nth_min = heappop(heap)
return nth_min
print(nth_smallest([4,1,7,3,8,5],3))
▶
4
from heapq import nsmallest, nlargest
print(nsmallest(3, [4,1,7,3,8,5])) # list를 인자로 받음
▶
[1, 3, 4]
print(nlargest(3, [4,1,7,3,8,5]))
▶
[8, 7, 5]
from heapq import heappush, heappop
def heap_sort(nums) :
heap = []
for num in nums :
heappush(heap, num)
sorted_nums = []
while heap:
sorted_nums.append(heappop(heap))
return sorted_nums
heap_sort([4,1,7,3,8,5])
▶
[1, 3, 4, 5, 7, 8]