Python PriorityQueue 实现,属性错误

Python PriorityQueue implementation, Attribute Error

目前正在为我的 CS 课程做作业,我 运行 遇到了 PriorityQueue 实现的问题。首先,这是我的 init 用于 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

但是,当 运行 对我的添加方法进行文档测试时,我收到一个属性错误,指出 str 对象没有属性 _less_than。我和我的教授谈过,他认为“可能只是一个打字错误”,所以经过几个小时的思考,我转向了 SO。

添加方法如下:

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)

错误如下:

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'

如有任何帮助,我们将不胜感激。

谢谢。

报错信息很清楚:

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

这显然告诉我们 _less_thanitem 上找不到。显然 itemstr 类型。由于 _less_than 是队列的 class 成员变量,而不是队列元素的成员变量,因此您需要在队列而不是项目上调用它。此外,_less_than 根据您发布的文档接受两个参数,而不是一个。

你的添加方法应该是这样的:

def add(self, item):
    if not self._queue:  # 1
        self._queue.append(item)
        return
    for i in range(len(self._queue)):
        if self._less_than(self._queue[i], item):   # 2
            self._queue.insert(i, item)
            return
    self._queue.append(item)  # 3

需要修改三处。

  1. 在您的代码中,您将 self._queue 与一个新的空队列进行比较。相反,您应该利用 Python 容器对象如果为空则具有布尔值 False 的事实。当你在列表中插入第一项时,你就完成了,需要 return;否则你将再次插入相同的项目。

  2. _less_than 是一个函数。它是在构造函数中分配的,因此它是 PriorityQueue 的成员。它的目的是比较两个项目。所以你需要用两个要比较的项目来调用它:一个是列表中的下一个项目,另一个是要插入的新项目。找到插入新项目的正确位置后,将其插入即可完成。那时你必须return。

  3. 如果_less_than函数returns False对于列表中已经存在的每个项目,您需要在末尾添加该项目。