【问题标题】:Python: How to set up a __str__ function in a PriorityQueuePython:如何在 PriorityQueue 中设置 __str__ 函数
【发布时间】:2015-04-28 23:15:05
【问题描述】:

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

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

上面是我的堆类,我的 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>

【问题讨论】:

  • 要选择使用哪一个,请参阅stackoverflow.com/questions/1436703/…。在这种情况下,您可能需要__str__
  • @augurar 我现在明白为什么我要使用__str__ 我将如何将它插入到我的 PQ 类中?
  • 我在下面的回答提供了更直接的响应,尽管它不会提供花哨的-&gt; 连接。只是为了记录,@rickcnagy 的解决方案有一个错误。 :-)

标签: python string function


【解决方案1】:

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

<PriorityQueue.PriorityQueue object at 0x01E95530>

在您的情况下,我们必须返回self.heap.heap 的项目,以-&gt; 分隔。这将有助于获得您所描述的输出:

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 的正是这个Heap,这反过来又为我们提供了我们想要的列表。

【讨论】:

  • 不应该将3 设为self.heap(而不是self.heap.heap)吗?。
  • @lifebalance 不,我很确定应该是self.heap.heap。这是因为在这种情况下selfPriorityQueue 实例,而PriorityQueue 具有包含Heap.heap 属性。我们实际上想要调用.heap 的正是这个Heap,这反过来又为我们提供了我们想要的列表。这有意义吗?
【解决方案2】:

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

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

相反,试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-12
    • 2011-04-03
    • 2018-05-07
    • 2017-05-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多