AttributeError: 'NoneType' object has no atribute 'insert'

AttributeError: 'NoneType' object has no atribute 'insert'

我的代码有问题。我不断收到以下错误:

AttributeError: 'NoneType' object has no attribute 'insert'

谁能告诉我为什么会出现此错误?这是我的代码和导致以下问题最多的代码片段。

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

这是我需要从中获取函数的主要堆函数。这是给我带来麻烦的代码部分。

    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

这是我的 PriorityQueue class,它调用函数并帮助我将它们实现到优先队列中。

从 MyHeap 导入堆

class PriorityQueue(object):

    def __init__(self):
        self.heap = None

    def enqueue(self, item, priority):
        '''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[0]


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

所以在这段代码中,入队调用了插入函数。

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

最后是我的测试代码:

from PriorityQueue import PriorityQueue

PQ = PriorityQueue()

PQ.enqueue(1, 200)
PQ.enqueue(2, 450)
PQ.enqueue(3, 204)

这可能是一个简单的修复,但有人知道为什么我总是收到属性错误吗?

那是因为你用 None:

初始化了 self.heap
class PriorityQueue(object):
    def __init__(self):
        self.heap = None

您可能应该使用 Heap():

进行初始化
class PriorityQueue(object):
    def __init__(self):
        self.heap = Heap()

您的代码还有其他问题:

你应该只用一个参数调用 self.heap.insert(你用两个参数调用):

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

你应该使用self.heap.size(),而不是Heap.size()

if self.heap.size() == 0:
    raise ValueError("Error your queue is empty.")

还有

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

您应该 return 来自 self.heap.delete_max() 的值:

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

first 必须 return 堆中的 [1] 元素,因为 [0] 总是 None:

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