优先级队列:Enqueue returns 'None' 而不是 int 值

Priority Queues: Enqueue returns 'None' instead of int value

我在 python 中的 PriorityQueue class 有问题。我想我一直都在设置它,现在我正在尝试测试它,但是当我打印出我正在排队的值时,我不断收到 "None" 这个词,这是不正确的。

这是我的测试代码,接下来是我的输出和预期输出:

from PriorityQueue import PriorityQueue

PQ = PriorityQueue()


print(PQ.enqueue(1, 10))
print(PQ.enqueue(2, 5))
print(PQ.enqueue(3, 90))
print(PQ)
print(PQ.size())

输出:

None
None
None
<PriorityQueue.PriorityQueue object at 0x01EE5250>
2

预期输出:

10
5
90
90,5,10
2

为什么要打印None这个词?我不知道为什么会那样做。这是我的 PriorityQueue class,它从中获取函数。

#PriorityQueue.py
from MyHeap import Heap


class PriorityQueue(object):

    def __init__(self):
        self.heap = Heap()

    def enqueue(self, priority, item):
        '''Post: Item is inserted with specified priority in the PQ.'''
        self.heap.insert((priority, item))

    def first(self):
        '''Post: Returns but does not remove the highest priority item from the PQ.'''
        return self.heap.size()


    def dequeue(self):
        '''Post: Removes and returns the highest priority item from the PQ.'''
        if self.heap.size() is None:
            raise ValueError("Error your queue is empty.")
        x = self.first()
        self.heap.delete_max()
        return x

    def size(self):
        '''Post: Returns the number of items in the PQ.'''
        return self.heap.size()

所有这些功能,或者大部分功能都来自我的自定义堆 class,就是这个。

class Heap(object):

    def __init__(self, items=None):

        '''Post: A heap is created with specified items.'''

        self.heap = [None]
        if items is None:
            self.heap_size = 0
        else:
            self.heap += items
            self.heap_size = len(items)
            self._build_heap()

    def size(self):

        '''Post: Returns the number of items in the heap.'''

        return self.heap_size

    def _heapify(self, position):

        '''Pre: Items from 0 to position - 1 satisfy the Heap property.
           Post: Heap Property is satisfied for the entire heap.'''

        item = self.heap[position]
        while position * 2 <= self.heap_size:
            child = position * 2
            # If the right child, determine the maximum of two children.
            if (child != self.heap_size and self.heap[child+1] > self.heap[child]):
                child += 1
            if self.heap[child] > item:
                self.heap[position] = self.heap[child]
                position = child
            else:
                break
        self.heap[position] = item

    def delete_max(self):

        '''Pre: Heap property is satisfied
           Post: Maximum element in heap is removed and returned. '''

        if self.heap_size > 0:
            max_item = self.heap[1]
            self.heap[1] = self.heap[self.heap_size]
            self.heap_size -= 1
            self.heap.pop()
            if self.heap_size > 0:
                self._heapify(1)
            return max_item

    def insert(self, item):

        '''Pre: Heap Property is Satisfied.
           Post: Item is inserted in proper location in heap.'''

        self.heap_size += 1
        # extend the length of the list.
        self.heap.append(None)
        position = self.heap_size
        parent = position // 2
        while parent > 0 and self.heap[parent] < item:
            # Move the item down.
            self.heap[position] = self.heap[parent]
            position = parent
            parent = position // 2
        # Puts the new item in the correct spot.
        self.heap[position] = item

    def _build_heap(self):

        ''' Pre: Self.heap has values in 1 to self.heap_size
           Post: Heap property is satisfied for entire heap. '''

        # 1 through self.heap_size.

        for i in range(self.heap_size // 2, 0, -1): # Stops at 1.
            self._heapify(i)

    def heapsort(self):

        '''Pre: Heap Property is satisfied.
           Post: Items are sorted in self.heap[1:self.sorted_size].'''

        sorted_size = self.heap_size

        for i in range(0, sorted_size -1):
            # Since delete_max calls pop to remove an item, we need to append a dummy value to avoid an illegal index.
            self.heap.append(None)
            item = self.delete_max()
            self.heap[sorted_size - i] = item

谁能告诉我它为什么不起作用的问题?我认为它应该是 return 的值。我也知道我的 PriorityQueue class 需要一个 iter,但我不知道它会是什么样子。谁能帮帮我?

您的 enqueue 方法没有 return 语句,因此它 returns None.

如果您希望 Python 类似于 Ruby 或 Scheme,并且 return 最后计算的表达式的值——好吧,Python不是 Ruby;最大的区别之一是,与 Ruby 不同,Python 是一种基于语句的语言,其中并非所有内容都是表达式,因此通常 没有 "last expression",只是最后一句,没有任何价值。

同时,从改变 self 的方法中 returning None 被认为是 Pythonic 要做的事情(参见 list.append,例如),所以你实际上正确地编写了你的​​代码,即使你不是故意的。 :)

这意味着 Python 不适合在其他一些语言中流行的方法链 "fluent style"。这是一个深思熟虑的设计选择;尽管 Guido 从未真正阐明原因,但考虑到单个巨大的表达式不会让您看到通过垂直 space 和水平缩进的控制流,就像语句链那样,阻止您为有意义的名称赋予有意义的名称中间值,更难用回溯或传统的步进调试器等进行调试。