기계는 거짓말하지 않는다

Python Priority Queue 본문

Python

Python Priority Queue

KillinTime 2021. 10. 13. 12:52

파이썬에서 우선순위 큐는 queue 모듈의 PriorityQueue를 import 하고 put. get으로 사용한다.

put 시에 임의로 순위를 지정해 줄 수 있다. (ex: q.put(1, "B"))

객체일 경우 조건에 따른 정렬 기준 설정이 가능하다.

부호에 따라 min, max가 바뀐다.

from queue import PriorityQueue

class TempClass:
    def __init__(self, string:str, index:int):
        if type(string) is not str: raise Exception("not string")
        if type(index) is not int: raise Exception("not integer")
        self.string = string
        self.index = index

    def __str__(self):
        return self.string + "-" + str(self.index)

    def __gt__(self, obj): # 정렬 기준
        if self.string == obj.string:
            return self.index > obj.index
        else:
            return self.string > obj.string	# min heap

q = PriorityQueue(maxsize=10) # maxsize를 지정하지 않아도 됨

# push
q.put(TempClass("A", 10))
q.put(TempClass("C", 5))
q.put(TempClass("C", 3))

# pop
print(q.get())

data = q.get()
print(data.string, data.index)
'''
결과
A-10
C 3
'''

 

'Python' 카테고리의 다른 글

Python 객체 유형, 자료형 확인  (0) 2021.12.06
Python XML ElementTree Read  (0) 2021.10.15
Python DataFrame 데이터 분리 후 csv 생성  (0) 2021.10.08
Python GUI PyQt5, QtDesigner  (0) 2021.10.07
Python DataFrame 특정 columns 추출  (0) 2021.10.05
Comments