파이썬 heapq, nsmallest vs heappop, heapify

개발공부를해보자·2025년 6월 10일

공부 정리

목록 보기
29/34
import heapq

# 원본 리스트
arr = [5, 1, 8, 3, 2]

# ✅ 1. heapq.nsmallest(): heapify 없이 바로 사용 가능, 원본 리스트 유지.
smallest_3 = heapq.nsmallest(3, arr)
print("nsmallest(3):", smallest_3)  # [1, 2, 3]
print("원본 유지됨:", arr)          # [5, 1, 8, 3, 2]

# ✅ 2. heappop(): heapify 후 사용, 원본 리스트 직접 변경
heapq.heapify(arr)                  # 힙으로 변환(하지 않으면 최솟값 말고 엉뚱한 값 나옴)
print("heapified arr:", arr)       # 내부 구조상 순서 달라짐
pop1 = heapq.heappop(arr)
print("첫 heappop():", pop1)        # 1
print("heappop 후 리스트:", arr)    # [2, 3, 8, 5]

# ✅ 3. sorted()[:k] vs nsmallest(k): 성능상 차이 있음 O(n log n) VS O(n log k)
sorted_k = sorted(arr)[:3]
print("sorted()[:3]:", sorted_k)    # [1, 2, 3]

# ✅ 4. 사용자 정의 정렬 기준 → key= 사용
people = [
    {'name': 'Alice', 'age': 25},
    {'name': 'Bob', 'age': 22},
    {'name': 'Carol', 'age': 30}
]

# 나이 기준으로 가장 어린 사람 2명
youngest_two = heapq.nsmallest(2, people, key=lambda p: p['age'])
print("나이 기준 nsmallest:", youngest_two)
# [{'name': 'Bob', 'age': 22}, {'name': 'Alice', 'age': 25}]

#cmp_to_key는 sorted()에서는 유용하지만, heapq.nsmallest()에서는 느리고 복잡해질 수 있으며 권장되지 않음.
profile
개발 공부하는 30대 비전공자 직장인

0개의 댓글