Search code examples
pythonlistpriority-queueimplementation

Is there a way to append to an object in python? Priority Queues


At the moment I am currently getting an error when it comes to my enQueue function. When I try to append a number to my object list, it says "'set' object has no attribute 'append'". I assume the problem has to do with how I am passing in the list but this is currently my problem. I have one hard-coded list of size 10 to work with because I didn't want to make a bigger list until I know what's going on. Any help would be appreciated. Also the comments that I have in the code is what I want to do as the end result. If you have any input on doing that, that would be more than helpful. At the moment though, I would like to just figure out how to not get that error. Thank you.

class PQ_List(object):

    def __init__(self, sampleList):
        print ("creates an unsorted list from passed in list")
        self.list = sampleList
        print (self.list)
#      
#        Returns the list 

    def enQueue(self, item):
        print ("adds an item to the PQ")
        self.list.append(item)
        print (self.list)
#       Add an item to the PQ 

    def deQueue(self):
        print ("removes the highest priority item from the PQ")
        self.list = self.list[1:]
        print (self.list)
#       Remove the highest priority item from the PQ 


    def sneakAPeek(self):
        print ("returns the highest priority in the PQ, but does not remove it")
        return self.list[0]
#
#       Return the highest priority item from the PQ, but don't remove it

    def isEmpty(self):
        print ("returns T if PQ is empty, F if PQ has entries")
        if len(self.list) > 0:
            return 'F'
        else:
            return 'T'
#       Return a T if PQ is empty, F if PQ is not empty 
#       
    def size(self):
        print ("returns number of items in queue")
        return len(self.list)
#       Return the number of items in the queue

sampleList = {1, 2, 5, 8, 4, 15, 13, 12, 10, 6}

my_listPQ = PQ_List(sampleList) #print first 10 numbers, use size to prove the rest is there
my_listPQ.enQueue(1500)
my_listPQ.deQueue()
my_listPQ.sneakAPeek()
my_listPQ.isEmpty()
my_listPQ.size()

I expect the output to add 1500 to the list for the enQueue function. Then do the following functions. Any help would be appreciated!


Solution

  • In python you use the square brackets [, ] for lists and the curly brackets {, } for sets.

    Hence, change the line

    sampleList = {1, 2, 5, 8, 4, 15, 13, 12, 10, 6}
    

    to

    sampleList = [1, 2, 5, 8, 4, 15, 13, 12, 10, 6]
    

    and you are good to go.