카테고리 없음

파이썬 heapq 활용하기

아놀드금자 2023. 6. 28. 20:49
728x90

import heapq 써줘야 한다

파이썬 내장 모듈

최소 힙(Min Heap)으로 구현

 

리스트를 힙으로 만들기 heapq.heapify(리스트)
힙에 요소 추가 heapq.heappush(힙이름, 요소)
힙 최소값 조회(제거) heapq.heappop(힙이름)
힙 최소값 조회(just 조회, 제거X) 힙이름[0]
import heapq

# 리스트를 힙으로 변환
nums = [5, 3, 8, 1, 2]
heapq.heapify(nums)
print(nums)  # [1, 2, 8, 5, 3]

# 요소 추가
heapq.heappush(nums, 4)
print(nums)  # [1, 2, 8, 5, 3, 4]

# 최솟값 조회 및 제거
min_value = heapq.heappop(nums)
print(min_value)  # 1
print(nums)  # [2, 3, 8, 5, 4]

# 최솟값 조회(제거하지 않음)
min_value = nums[0]
print(min_value)  # 2

# 리스트를 힙으로 정렬
nums = [5, 3, 8, 1, 2]
heapq.heapify(nums)
sorted_nums = [heapq.heappop(nums) for _ in range(len(nums))]
print(sorted_nums)  # [1, 2, 3, 5, 8]

# 최대 힙 구현
nums = [5, 3, 8, 1, 2]
max_heap = [-num for num in nums]
heapq.heapify(max_heap)
max_value = -heapq.heappop(max_heap)
print(max_value)  # 8
728x90