0
0

Pythonの優先度付きキューの説明と改変

Posted at

記事を書くことは初めてなのでうまく書けていないです
私が得意としているのは競技プログラミングなので細かい仕様はわかっていない可能性があります

書き途中だけど下書きにしないで投稿します

優先度付きキュー(Priority Quque)とは <-知ってる人は読まなくていいよ

ある箱に物を入れたり取り出したりが得意なデータ構造です。
取り出す際はある一定のルールに基づいて取り出します。
例えば箱の中の最小の値を取り出し続けるなど…

こんな感じ

箱(常に最小の値を取り出せる)=[]
3を入れる 箱:[3]
2を入れる 箱:[3, 2]
4を入れる 箱:[3, 2, 4]
取り出す ->2
取り出す ->3
取り出す ->4

Pythonにある優先度付きキューの種類

Pythonには3つ使える優先度付きキューがある。
heapqモジュール
queueパッケージのPriorityQueueモジュール
asynicパッケージのPriorityQueueモジュール

test.py
import heapq
from queue import PriorityQueue
from asyncio import PriorityQueue

今回改変するのはheapqの方

test.py
from heapq import heapify, heappop, heappush
class heapq:
    def __init__(self,lst=[],smaller=True) -> None:
        self.q=list()
        self.d=1 if smaller else -1
        for v in lst:
            heappush(self.q,v*self.d)
    def push(self,value):
        heappush(self.q,value*self.d)
    def pop(self):
        return heappop(self.q)*self.d
    def __len__(self):
        return len(self.q)
    def __str__(self):
        return f"heapq {list(map(lambda x:x*self.d,self.q))}"
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0