簡體   English   中英

Python:如何在PriorityQueue中設置__str__函數

[英]Python: How to set up a __str__ function in a PriorityQueue

我做了一個優先級隊列,其功能使用了我的二進制堆函數。 但是,在我的測試文件中,我試圖將“隊列”打印出來,看起來像這樣。

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取用的Heap類:下面是我的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>

好的, __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 ,我們實際上要調用.heap上,后者又為我們提供了我們要去的名單。

編輯 :我試圖執行以下操作:

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

相反,請嘗試以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM