How do I keep the largest few items without sorting everything?
Find the largest trades with heapq.nlargest, see how a heap keeps its smallest item first, and keep a running top five as trades arrive.
After this lesson, you can find the largest few trades and keep a running top five as new trades arrive.
How do I find the largest trades in one call?
heapq.nlargest(5, sizes) returns the five largest sizes, largest first, without sorting the whole list. For seven made-up trades, it returns 900, 400, 400, 300 and 150 shares, the same as sorted(sizes, reverse=True)[:5], which sorts every trade first.
The trades arrive in order, each a size in shares and a ticker. key= makes nlargest compare one field and return the whole trade.
The following box finds the five largest sizes and the two largest trades.
On a million trades, nlargest keeps only five candidates while it reads the list, which takes far less time than sorting all of them.
How do I keep the top five as trades arrive?
A heap is a list kept in an order where position 0 holds the smallest item, so best[0] is the smallest of the five sizes kept. Each new size enters while fewer than five are kept, and after that replaces the smallest only when it is larger. The last trade, CCC’s 400 shares, replaces the 50.
heapq.heappush(best, size) adds a size and keeps the heap order, and heapq.heapreplace(best, size) removes the smallest and adds the new size in one step. Sorting best for printing leaves the heap itself unchanged.
The following box keeps the top five as each trade arrives.
best = []for size in sizes:iflen(best) <5: heapq.heappush(best, size)elif size > best[0]: heapq.heapreplace(best, size)print(size, sorted(best, reverse=True))