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_72777d74d55e59c9.png)
![[Python Cheatsheet] 29. operator - 연산자 함수와 효율적 접근자](/post/python-cheatsheet/efficient-operator-module-guide-for-sorting-functional-patterns/wordcloud_hu_69b3cc6dc63a3941.png)
![[Python Cheatsheet] 30. collections 심화 - deque/namedtuple/ChainMap](/post/python-cheatsheet/effective-collections-deque-namedtuple-chainmap-advanced-guide/wordcloud_hu_cd891a80d48aba0f.png)
![[Python Cheatsheet] 31. heapq & bisect - 우선순위 큐/이진 검색 패턴](/post/python-cheatsheet/heapq-bisect-priority-queue-binary-search-guide/wordcloud_hu_2b6efde7c9bc727c.png)
![[Python Cheatsheet] 32. contextlib 심화 - suppress, redirect, ExitStack](/post/python-cheatsheet/contextlib-advanced-suppress-redirect-exitstack-nullcontext-examples/wordcloud_hu_ac7b663d88a59d6d.png)
![[Python Cheatsheet] 33. textwrap - 텍스트 정렬과 줄바꿈](/post/python-cheatsheet/textwrap-formatting-multiline-word-wrap-guide/wordcloud_hu_b4f2dc39588eb07.png)
![[Python Cheatsheet] 04. Collections - list/tuple/set 패턴](/post/python-cheatsheet/fast-list-tuple-set-guide-patterns-collection-copy-sort-unpack/wordcloud_hu_bd6bf3a251c6426.png)
![[Python Cheatsheet] 61. Profiling - cProfile/py-spy 성능 분석](/post/python-cheatsheet/profiling-cprofile-pyspy-performance-analysis-guide/wordcloud_hu_e5d0dcaf802b0e2d.png)
![[Python Cheatsheet] 63. asyncio - 비동기 최소 패턴](/post/python-cheatsheet/async-io-patterns-concurrency-coroutine-async-await-guide/wordcloud_hu_e60faafd6849ed23.png)
![[Python Cheatsheet] 64. Concurrency - threading/multiprocessing 선택](/post/python-cheatsheet/concurrency-guide-threading-vs-multiprocessing-explained-fast/wordcloud_hu_fa87651745dbb8a2.png)