我试图将生成器用于一个用例,在这个用例中,我们必须跟踪字符串流中的k个“最大”元素。我想做的是将元素添加到列表中,直到它们到达元素k,然后heapify,然后从那里继续流,使用元素逐个维护堆。我对使用发电机有点陌生,所以非常感谢您的帮助
def my_generator(stream):
for string in stream:
yield string
def top_k(k,stream):
count = 0
min_heap = []
for string in stream:
if count >= k:
break
min_heap.append((len(string),string))
count += 1
print(min_heap)
heapq.heapify(min_heap)
for string in stream:
heapq.heappushpop(min_heap,(len(string),string))
return heapq.nsmallest(k,min_heap)
strings = ["This", "whatis", "going", "in"]
stream = my_generator(strings)
output = top_k(2,stream)
print(output)
您的断点和随后的流恢复会导致元素“丢失”到空中
这是您的代码,但不会丢失任何元素:
相关问题 更多 >
编程相关推荐