Click here to Skip to main content
15,914,071 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Priority function for Priority Queue not returning string in Python - Stack Overflow[^]

I'm trying to implement a priority queue using an array list of my PQElement’s. I am stuck on dequeueing from the priority queue the PQ-element with the greatest priority so that I can print elements of the priority queue into a string, in order of decreasing priority.

Any idea on how to go about this?


What I have tried:

class PQElement:
    def __init__(self, v, p):
        self.val = v
        self.priority = p
            
    def __str__(self):
        return "("+str(self.val)+","+str(self.priority)+")"
        
class PQueue:
    def __init__(self):
        self.inList = []
        
    def __len__(self):
        return len(self.inList)

    def ___str__(self,):
        return str(self.inList)
    
    def enq(self, e): # insert (tail)
        self.inList.append(e)   
        
    def deq(self): # remove
        if len(self)==0:
            raise IndexError("deq from empty queue")
        max_priority = self.inList[0].priority
        max_idx = 0
        for idx, elmt in enumerate(self.inList):
            if elmt.priority > max_priority:
                max_priority = elmt.priority
                max_idx = idx
        return self.inList.pop(max_idx)
Posted
Comments
Richard MacCutchan 27-Oct-21 3:32am    
You should ask the person in SO who posted that answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900