Search code examples
pythonpriority-queue

How can I create priority queue that contains my class implementation?


I got task class that I implemented, I want to insert all my tasks into priority queue, there is one in python? Do I need to implement some func inside my class to make it comparable?

Each class got priority number.


Solution

  • There is indeed a priority queue in Python, see here: https://docs.python.org/3/library/queue.html#Queue.PriorityQueue

    Here is a simple example:

    from queue import PriorityQueue
    
    q = PriorityQueue()
    
    q.put((2, 'code'))
    q.put((1, 'eat'))
    q.put((3, 'sleep'))
    
    while not q.empty():
        next_item = q.get()
        print(next_item)
    
    # Result:
    #   (1, 'eat')
    #   (2, 'code')
    #   (3, 'sleep')
    

    You can also use heapq as well.

    Can't comment on your implementation without knowing more information...