Python Priority Queue

김신영·2025년 5월 4일

Python

목록 보기
8/10
post-thumbnail
라이브러리스레드 안전성설치 필요특징
heapq가볍고 빠른 Min-Heap
queue.PriorityQueue스레드 안전
sortedcontainers정렬된 리스트 기반
heapdict키 기반 힙 구조 지원
pqueue다양한 정책 지원

1. heapq 모듈 (표준 라이브러리)

  • 설명: 최소 힙(Min-Heap) 기반의 우선순위 큐를 제공합니다.

  • 특징:

    • 표준 라이브러리이므로 별도 설치 불필요
    • heapify, heappush, heappop 함수 제공
  • 예제:

    import heapq
    
    heap = []
    heapq.heappush(heap, (2, "task2"))
    heapq.heappush(heap, (1, "task1"))
    heapq.heappush(heap, (3, "task3"))
    
    while heap:
        priority, task = heapq.heappop(heap)
        print(priority, task)

2. queue.PriorityQueue (표준 라이브러리)

  • 설명: thread-safe를 보장하는 우선순위 큐입니다.

  • 특징:

    • 내부적으로 heapq를 사용
    • 멀티스레드 환경에서 안전하게 사용 가능
  • 예제:

    from queue import PriorityQueue
    
    pq = PriorityQueue()
    pq.put((2, "task2"))
    pq.put((1, "task1"))
    pq.put((3, "task3"))
    
    while not pq.empty():
        priority, task = pq.get()
        print(priority, task)

3. sortedcontainers 라이브러리

  • 설명: 정렬된 리스트 기반의 컬렉션을 제공하며, 우선순위 큐로도 사용 가능

  • 설치:

    pip install sortedcontainers
  • 예제:

    from sortedcontainers import SortedList
    
    pq = SortedList()
    pq.add((2, "task2"))
    pq.add((1, "task1"))
    pq.add((3, "task3"))
    
    while pq:
        priority, task = pq.pop(0)
        print(priority, task)

4. heapdict 라이브러리

  • 설명: key-value 형태로 사용할 수 있는 우선순위 힙

  • 설치:

    pip install heapdict
  • 예제:

    from heapdict import heapdict
    
    hd = heapdict()
    hd["task1"] = 1
    hd["task2"] = 2
    hd["task3"] = 3
    
    while hd:
        task, priority = hd.popitem()
        print(priority, task)

5. pqueue 라이브러리 (비표준)

  • 설명: min, max, fifo 등 다양한 정책을 지원하는 큐

  • 설치:

    pip install pqueue
  • 예제:

    from pqueue import PriorityQueue
    
    pq = PriorityQueue()
    pq.put(2, "task2")
    pq.put(1, "task1")
    pq.put(3, "task3")
    
    while not pq.empty():
        print(pq.get())
profile
Hello velog!

0개의 댓글