有没有一种方法可以附加到python中的对象?优先队列

时间:2019-03-23 10:38:43

标签: python list priority-queue implementation

目前,我的enQueue函数遇到错误。当我尝试将数字附加到对象列表时,它说“'set'对象没有属性'append'”。我认为问题与我在列表中的传递方式有关,但这是当前的问题。我有一个大小为10的硬编码列表,因为在知道发生了什么事情之前,我不想做更大的列表。任何帮助,将不胜感激。我在代码中的注释也是我想要做的最终结果。如果您对此有任何意见,那将大有帮助。不过,目前,我只想弄清楚如何避免出现该错误。谢谢。

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()

我希望输出将1500添加到enQueue函数的列表中。然后执行以下功能。 任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

在python中,将方括号[]用于列表,将大括号{}用于集合。

因此,更改行

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

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

你很好。

答案 1 :(得分:0)

更改

sampleList = {1, 2, 5, 8, 4, 15, 13, 12, 10, 6}  # this is set and don't have append

对此:

sampleList = [1, 2, 5, 8, 4, 15, 13, 12, 10, 6]  # this is list