Python:如何在PriorityQueue中设置__str__函数

时间:2015-04-28 23:15:05

标签: python string function

我创建了一个优先级队列,其功能使用我的二进制堆函数。但是,在我的测试文件中,我试图打印出我的队列,看起来像这样。

Your queue looks like this: 15 -> 45 -> 10 -> 100

在某个地方,但是它会一直打印出存储队列的位置而不是队列中的项目,例如:

<PriorityQueue.PriorityQueue object at 0x01E95530>

我读了pythonDocs并得出结论我需要一个 str 函数。但是,我在创建它时遇到问题任何人都可以帮我解决它的样子吗?非常感谢。这是我的全部代码。

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

上面是我的Heap类,我的PriorityQueue取自: 下面是我的PQ类和我的测试文件。

#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))
        return 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()
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())
编辑:我试图做以下事情:

 def __str__(self):
        return str(self.heap)

这只打印出来:

<MyHeap.Heap object at 0x01E255F0>

2 个答案:

答案 0 :(得分:2)

好的,__str__的想法是返回某种以人类可读的方式表示对象的字符串。您必须构造字符串,然后将打印而不是

<PriorityQueue.PriorityQueue object at 0x01E95530>

在您的情况下,我们必须退回由self.heap.heap分隔的->项。这可以像你描述的那样获得输出:

def __str__(self):
    if self.size():
        heap_items = [str(i) for i in self.heap.heap if i]
        heap_items_str = ' -> '.join(heap_items)
        return "Your queue looks like this: {}".format(heap_items_str)
    else:
        return "Your queue is empty."

请注意,我们使用的是self.heap.heap,而不是self.heap,因为在这种情况下selfPriorityQueue个实例,而PriorityQueue的.heap属性包含一个Heap。这个Heap我们实际上想要打{{1​​}},这反过来又为我们提供了我们正在寻找的列表。

答案 1 :(得分:0)

  

编辑:我尝试执行以下操作:

def __str__(self):
    return str(self.heap)

相反,试试这个:

def __str__(self):
    return self.heap.__str__()