heapq는 우선순위 큐를, bisect는 정렬된 리스트에서 이진 검색을 제공합니다. 이 치트시트는 최소/최대 힙, 정렬 유지 삽입, nlargest/nsmallest 패턴을 정리합니다.
언제 이 치트시트를 보나?
- 가장 작은/큰 N개를 효율적으로 찾고 싶을 때
- 정렬된 리스트를 유지하면서 삽입/검색하고 싶을 때
핵심 패턴
heapq: 리스트를 힙으로 사용 (최소 힙)bisect: 정렬된 리스트에서 O(log n) 검색/삽입 위치 찾기- 최대 힙: 값에
-를 붙여서 최소 힙으로 구현
heapq - 우선순위 큐
| |
| |
| |
최대 힙 구현
| |
nlargest / nsmallest
| |
성능 팁: 전체 정렬
sorted()[-n:]보다nlargest(n)이 효율적 (n이 작을 때)
bisect - 정렬된 리스트 이진 검색
| |
| |
실전 패턴
| |
| |
| |
자주 하는 실수/주의점
- heapq는 최소 힙만 제공: 최대 힙은
-붙여서 구현 - heap[0]만 최소값 보장: 나머지 순서는 정렬 아님
- bisect.insort는 O(n): 삽입 위치 찾기는 O(log n)이지만, 실제 삽입은 O(n)
- 리스트가 정렬되어 있어야 함: bisect는 정렬된 리스트에서만 동작
- nlargest/nsmallest 선택 기준:
- n이 작으면:
nlargest(n, data)사용 - n이 1이면:
min(data)/max(data)사용 - n이 크면:
sorted(data)[:n]사용
- n이 작으면:
![Featured image of post [Python Cheatsheet] 31. heapq & bisect - 우선순위 큐/이진 검색 패턴](/post/python-cheatsheet/heapq-bisect-priority-queue-binary-search-guide/wordcloud_hu_fef7eab42219c53a.webp)
![[Python Cheatsheet] 29. operator - 연산자 함수와 효율적 접근자](/post/python-cheatsheet/efficient-operator-module-guide-for-sorting-functional-patterns/wordcloud_hu_ccfe1db60a2f866a.webp)
![[Python Cheatsheet] 30. collections 심화 - deque/namedtuple/ChainMap](/post/python-cheatsheet/effective-collections-deque-namedtuple-chainmap-advanced-guide/wordcloud_hu_d825cfa100af3bf6.webp)
![[Python Cheatsheet] 31. heapq & bisect - 우선순위 큐/이진 검색 패턴](/post/python-cheatsheet/heapq-bisect-priority-queue-binary-search-guide/wordcloud_hu_79e1ae223a5bd420.webp)
![[Python Cheatsheet] 32. contextlib 심화 - suppress, redirect, ExitStack](/post/python-cheatsheet/contextlib-advanced-suppress-redirect-exitstack-nullcontext-examples/wordcloud_hu_63614113bfad58c2.webp)
![[Python Cheatsheet] 33. textwrap - 텍스트 정렬과 줄바꿈](/post/python-cheatsheet/textwrap-formatting-multiline-word-wrap-guide/wordcloud_hu_196f121220eb0e69.webp)
![[Python Cheatsheet] 50. hashlib & secrets - 해시/보안 난수 패턴](/post/python-cheatsheet/hashlib-secrets-hash-random-security-tips-token-checksum-digest/wordcloud_hu_e76d052b870185b4.webp)
![[Python Cheatsheet] 21. Enum & Flag - 열거형 실전 패턴](/post/python-cheatsheet/enum-flag-intenum-strenum-auto-bitwise-guide-best-patterns/wordcloud_hu_c5e80eb17669433.webp)
![[Python Cheatsheet] 23. match-case - 구조적 패턴 매칭 (Py3.10+)](/post/python-cheatsheet/structural-pattern-matching-switch-guide-py310-py311-code-examples/wordcloud_hu_2cda0fd47115850c.webp)
![[Python Cheatsheet] 24. ABC - 추상 클래스 정의 패턴](/post/python-cheatsheet/abstract-base-class-interface-abc-usage-oop-patterns-guide/wordcloud_hu_8452ac7fa3f0f133.webp)