import heapq # 모듈 import
heap = [] # heap 생성
# heap에 원소 추가
heapq.heappush(heap, 1)
heapq.heappush(heap, 3)
heapq.heappush(heap, 4)
heapq.heappush(heap, 2)
print(heap)
>>> [1, 2, 4, 3]
# heap에서 원소 삭제
print(heapq.heappop(heap)) # 가장 작은 원소 삭제 후 그 값 리턴
print(heap)
>>> 1
>>> [2, 4, 3]
# 최소 값
print(heap[0]
>>> 2
# 리스트 ▶️ 힙
heap = [2, 5, 1, 4, 9]
heapq.heapify(heap)
print(heap)
>>> [1, 4, 2, 5, 9]
import heapq
def heapsort(iterable):
h = []
for value in iterable:
heapq.heappush(h, value)
return [heapq.heappop(h) for i in range(len(h))]
print(heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0]))
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# while문 이용
def heap_sort(nums):
h = []
for num in nums:
heapq.heappush(h1, num)
sorted_nums = []
while h:
sorted_nums.append(heapq.heappop(h))
return sorted_nums
print(heap_sort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0]))
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
import heapq
nums = [5, 1, 7, 3, 9]
heap = []
for num in nums:
heapq.heappush(heap, (-num, num)) # (우선 순위, 값)
while heap:
print(heapq.heappop(heap)[1])
>>> 9
>>> 7
>>> 5
>>> 3
>>> 1
참고: https://jungeun960.tistory.com/146?category=468716
https://docs.python.org/ko/3/library/heapq.html#