gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:43:50 25 4
gpt4 key购买 nike

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

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>

最佳答案

好吧,__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,因为在本例中 self 是一个 PriorityQueue 实例,并且 PriorityQueue 有一个包含 Heap 的 .heap 属性。我们实际上想要调用 .heap 的就是这个 Heap,它反过来又为我们提供了我们想要的列表。

关于Python:如何在 PriorityQueue 中设置 __str__ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29931568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com