NISHIO Hirokazu[Translate]
Best Kの取得
from heapq
Best Kの取得
サイズがkを超えたらpop
python
from random import shuffle xs = list(range(100)) shuffle(xs) K = 3 queue = xs[:K] heapify(queue) for x in xs[K:]: heappush(queue, x) heappop(queue) print(queue) # => [97, 98, 99]


"Engineer's way of creating knowledge" the English version of my book is now available on [Engineer's way of creating knowledge]

(C)NISHIO Hirokazu / Converted from [Scrapbox] at [Edit]