Search code examples
pythonpriority-queue

Python PriorityQueue implementation, Attribute Error


Currently working on an assignment for my CS course and Ive run into a problem with my implementation of a PriorityQueue. First off, heres my init for the class:

class PriorityQueue(Container):
    
    def __init__(self, less_than):
        """Initialize this to an empty PriorityQueue.

        @type self: PriorityQueue
        @type less_than: Callable[[Object, Object], bool]
            Determines the relative priority of two elements of the queue.
            If x._less_than(y) is true, then x has higher priority than y.
        @rtype: None
        """

        self._queue = []
        self._less_than = less_than

However, when running doctests for my add method, I'm being returned an Attribute Error stating that str objects have no attribute _less_than. Ive spoken to my prof who brushed it off as, "probably just a typo" so after many hours mulling over this Ive turned to SO.

Heres the add method:

def add(self, item):
    if self._queue == []:
        self._queue.append(item)
    for i in range(len(self._queue)):
        if item._less_than(self._queue[i]):
            self._queue.insert(i, item)

And heres the error:

File ", line 99, in add
Failed example:
    pq.add('arju')
Exception raised:
    Traceback (most recent call last):
      File "/Applications/PyCharm 
CE.app/Contents/helpers/pycharm/docrunner.py", line 140, in __run
        compileflags, 1), test.globs)
      File "<doctest add[3]>", line 1, in <module>
        pq.add('arju')
      File "", line 113, in add
    if item._less_than(self._queue[i]):
AttributeError: 'str' object has no attribute '_less_than'

Any help at all would be greatly appreciated.

Thanks.


Solution

  • The error message is very clear:

    if item._less_than(self._queue[i]):
        AttributeError: 'str' object has no attribute '_less_than'
    

    This obviously tells us that _less_than is not found on item. And clearly item is of type str. Since _less_than is a class member variable of the queue, not of an element of the queue, you need to invoke it on the queue, not the item. Also, _less_than as per the documentation you posted takes two arguments, not one.