| 1 |
"""Heap queue algorithm (a.k.a. priority queue). |
| 2 |
|
| 3 |
Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for |
| 4 |
all k, counting elements from 0. For the sake of comparison, |
| 5 |
non-existing elements are considered to be infinite. The interesting |
| 6 |
property of a heap is that a[0] is always its smallest element. |
| 7 |
|
| 8 |
Usage: |
| 9 |
|
| 10 |
heap = [] # creates an empty heap |
| 11 |
heappush(heap, item) # pushes a new item on the heap |
| 12 |
item = heappop(heap) # pops the smallest item from the heap |
| 13 |
item = heap[0] # smallest item on the heap without popping it |
| 14 |
heapify(x) # transforms list into a heap, in-place, in linear time |
| 15 |
item = heappushpop(heap, item) # pushes a new item and then returns |
| 16 |
# the smallest item; the heap size is unchanged |
| 17 |
item = heapreplace(heap, item) # pops and returns smallest item, and adds |
| 18 |
# new item; the heap size is unchanged |
| 19 |
|
| 20 |
Our API differs from textbook heap algorithms as follows: |
| 21 |
|
| 22 |
- We use 0-based indexing. This makes the relationship between the |
| 23 |
index for a node and the indexes for its children slightly less |
| 24 |
obvious, but is more suitable since Python uses 0-based indexing. |
| 25 |
|
| 26 |
- Our heappop() method returns the smallest item, not the largest. |
| 27 |
|
| 28 |
These two make it possible to view the heap as a regular Python list |
| 29 |
without surprises: heap[0] is the smallest item, and heap.sort() |
| 30 |
maintains the heap invariant! |
| 31 |
""" |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
__about__ = """Heap queues |
| 36 |
|
| 37 |
[explanation by François Pinard] |
| 38 |
|
| 39 |
Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for |
| 40 |
all k, counting elements from 0. For the sake of comparison, |
| 41 |
non-existing elements are considered to be infinite. The interesting |
| 42 |
property of a heap is that a[0] is always its smallest element. |
| 43 |
|
| 44 |
The strange invariant above is meant to be an efficient memory |
| 45 |
representation for a tournament. The numbers below are `k', not a[k]: |
| 46 |
|
| 47 |
0 |
| 48 |
|
| 49 |
1 2 |
| 50 |
|
| 51 |
3 4 5 6 |
| 52 |
|
| 53 |
7 8 9 10 11 12 13 14 |
| 54 |
|
| 55 |
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
| 56 |
|
| 57 |
|
| 58 |
In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In |
| 59 |
a usual binary tournament we see in sports, each cell is the winner |
| 60 |
over the two cells it tops, and we can trace the winner down the tree |
| 61 |
to see all opponents s/he had. However, in many computer applications |
| 62 |
of such tournaments, we do not need to trace the history of a winner. |
| 63 |
To be more memory efficient, when a winner is promoted, we try to |
| 64 |
replace it by something else at a lower level, and the rule becomes |
| 65 |
that a cell and the two cells it tops contain three different items, |
| 66 |
but the top cell "wins" over the two topped cells. |
| 67 |
|
| 68 |
If this heap invariant is protected at all time, index 0 is clearly |
| 69 |
the overall winner. The simplest algorithmic way to remove it and |
| 70 |
find the "next" winner is to move some loser (let's say cell 30 in the |
| 71 |
diagram above) into the 0 position, and then percolate this new 0 down |
| 72 |
the tree, exchanging values, until the invariant is re-established. |
| 73 |
This is clearly logarithmic on the total number of items in the tree. |
| 74 |
By iterating over all items, you get an O(n ln n) sort. |
| 75 |
|
| 76 |
A nice feature of this sort is that you can efficiently insert new |
| 77 |
items while the sort is going on, provided that the inserted items are |
| 78 |
not "better" than the last 0'th element you extracted. This is |
| 79 |
especially useful in simulation contexts, where the tree holds all |
| 80 |
incoming events, and the "win" condition means the smallest scheduled |
| 81 |
time. When an event schedule other events for execution, they are |
| 82 |
scheduled into the future, so they can easily go into the heap. So, a |
| 83 |
heap is a good structure for implementing schedulers (this is what I |
| 84 |
used for my MIDI sequencer :-). |
| 85 |
|
| 86 |
Various structures for implementing schedulers have been extensively |
| 87 |
studied, and heaps are good for this, as they are reasonably speedy, |
| 88 |
the speed is almost constant, and the worst case is not much different |
| 89 |
than the average case. However, there are other representations which |
| 90 |
are more efficient overall, yet the worst cases might be terrible. |
| 91 |
|
| 92 |
Heaps are also very useful in big disk sorts. You most probably all |
| 93 |
know that a big sort implies producing "runs" (which are pre-sorted |
| 94 |
sequences, which size is usually related to the amount of CPU memory), |
| 95 |
followed by a merging passes for these runs, which merging is often |
| 96 |
very cleverly organised[1]. It is very important that the initial |
| 97 |
sort produces the longest runs possible. Tournaments are a good way |
| 98 |
to that. If, using all the memory available to hold a tournament, you |
| 99 |
replace and percolate items that happen to fit the current run, you'll |
| 100 |
produce runs which are twice the size of the memory for random input, |
| 101 |
and much better for input fuzzily ordered. |
| 102 |
|
| 103 |
Moreover, if you output the 0'th item on disk and get an input which |
| 104 |
may not fit in the current tournament (because the value "wins" over |
| 105 |
the last output value), it cannot fit in the heap, so the size of the |
| 106 |
heap decreases. The freed memory could be cleverly reused immediately |
| 107 |
for progressively building a second heap, which grows at exactly the |
| 108 |
same rate the first heap is melting. When the first heap completely |
| 109 |
vanishes, you switch heaps and start a new run. Clever and quite |
| 110 |
effective! |
| 111 |
|
| 112 |
In a word, heaps are useful memory structures to know. I use them in |
| 113 |
a few applications, and I think it is good to keep a `heap' module |
| 114 |
around. :-) |
| 115 |
|
| 116 |
-------------------- |
| 117 |
[1] The disk balancing algorithms which are current, nowadays, are |
| 118 |
more annoying than clever, and this is a consequence of the seeking |
| 119 |
capabilities of the disks. On devices which cannot seek, like big |
| 120 |
tape drives, the story was quite different, and one had to be very |
| 121 |
clever to ensure (far in advance) that each tape movement will be the |
| 122 |
most effective possible (that is, will best participate at |
| 123 |
"progressing" the merge). Some tapes were even able to read |
| 124 |
backwards, and this was also used to avoid the rewinding time. |
| 125 |
Believe me, real good tape sorts were quite spectacular to watch! |
| 126 |
From all times, sorting has always been a Great Art! :-) |
| 127 |
""" |
| 128 |
|
| 129 |
__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge', |
| 130 |
'nlargest', 'nsmallest', 'heappushpop'] |
| 131 |
|
| 132 |
def heappush(heap, item): |
| 133 |
"""Push item onto heap, maintaining the heap invariant.""" |
| 134 |
heap.append(item) |
| 135 |
_siftdown(heap, 0, len(heap)-1) |
| 136 |
|
| 137 |
def heappop(heap): |
| 138 |
"""Pop the smallest item off the heap, maintaining the heap invariant.""" |
| 139 |
lastelt = heap.pop() |
| 140 |
if heap: |
| 141 |
returnitem = heap[0] |
| 142 |
heap[0] = lastelt |
| 143 |
_siftup(heap, 0) |
| 144 |
return returnitem |
| 145 |
return lastelt |
| 146 |
|
| 147 |
def heapreplace(heap, item): |
| 148 |
"""Pop and return the current smallest value, and add the new item. |
| 149 |
|
| 150 |
This is more efficient than heappop() followed by heappush(), and can be |
| 151 |
more appropriate when using a fixed-size heap. Note that the value |
| 152 |
returned may be larger than item! That constrains reasonable uses of |
| 153 |
this routine unless written as part of a conditional replacement: |
| 154 |
|
| 155 |
if item > heap[0]: |
| 156 |
item = heapreplace(heap, item) |
| 157 |
""" |
| 158 |
returnitem = heap[0] |
| 159 |
heap[0] = item |
| 160 |
_siftup(heap, 0) |
| 161 |
return returnitem |
| 162 |
|
| 163 |
def heappushpop(heap, item): |
| 164 |
"""Fast version of a heappush followed by a heappop.""" |
| 165 |
if heap and heap[0] < item: |
| 166 |
item, heap[0] = heap[0], item |
| 167 |
_siftup(heap, 0) |
| 168 |
return item |
| 169 |
|
| 170 |
def heapify(x): |
| 171 |
"""Transform list into a heap, in-place, in O(len(x)) time.""" |
| 172 |
n = len(x) |
| 173 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
for i in reversed(range(n//2)): |
| 179 |
_siftup(x, i) |
| 180 |
|
| 181 |
def _heappop_max(heap): |
| 182 |
"""Maxheap version of a heappop.""" |
| 183 |
lastelt = heap.pop() |
| 184 |
if heap: |
| 185 |
returnitem = heap[0] |
| 186 |
heap[0] = lastelt |
| 187 |
_siftup_max(heap, 0) |
| 188 |
return returnitem |
| 189 |
return lastelt |
| 190 |
|
| 191 |
def _heapreplace_max(heap, item): |
| 192 |
"""Maxheap version of a heappop followed by a heappush.""" |
| 193 |
returnitem = heap[0] |
| 194 |
heap[0] = item |
| 195 |
_siftup_max(heap, 0) |
| 196 |
return returnitem |
| 197 |
|
| 198 |
def _heapify_max(x): |
| 199 |
"""Transform list into a maxheap, in-place, in O(len(x)) time.""" |
| 200 |
n = len(x) |
| 201 |
for i in reversed(range(n//2)): |
| 202 |
_siftup_max(x, i) |
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
def _siftdown(heap, startpos, pos): |
| 208 |
newitem = heap[pos] |
| 209 |
|
| 210 |
|
| 211 |
while pos > startpos: |
| 212 |
parentpos = (pos - 1) >> 1 |
| 213 |
parent = heap[parentpos] |
| 214 |
if newitem < parent: |
| 215 |
heap[pos] = parent |
| 216 |
pos = parentpos |
| 217 |
continue |
| 218 |
break |
| 219 |
heap[pos] = newitem |
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
def _siftup(heap, pos): |
| 261 |
endpos = len(heap) |
| 262 |
startpos = pos |
| 263 |
newitem = heap[pos] |
| 264 |
|
| 265 |
childpos = 2*pos + 1 |
| 266 |
while childpos < endpos: |
| 267 |
|
| 268 |
rightpos = childpos + 1 |
| 269 |
if rightpos < endpos and not heap[childpos] < heap[rightpos]: |
| 270 |
childpos = rightpos |
| 271 |
|
| 272 |
heap[pos] = heap[childpos] |
| 273 |
pos = childpos |
| 274 |
childpos = 2*pos + 1 |
| 275 |
|
| 276 |
|
| 277 |
heap[pos] = newitem |
| 278 |
_siftdown(heap, startpos, pos) |
| 279 |
|
| 280 |
def _siftdown_max(heap, startpos, pos): |
| 281 |
'Maxheap variant of _siftdown' |
| 282 |
newitem = heap[pos] |
| 283 |
|
| 284 |
|
| 285 |
while pos > startpos: |
| 286 |
parentpos = (pos - 1) >> 1 |
| 287 |
parent = heap[parentpos] |
| 288 |
if parent < newitem: |
| 289 |
heap[pos] = parent |
| 290 |
pos = parentpos |
| 291 |
continue |
| 292 |
break |
| 293 |
heap[pos] = newitem |
| 294 |
|
| 295 |
def _siftup_max(heap, pos): |
| 296 |
'Maxheap variant of _siftup' |
| 297 |
endpos = len(heap) |
| 298 |
startpos = pos |
| 299 |
newitem = heap[pos] |
| 300 |
|
| 301 |
childpos = 2*pos + 1 |
| 302 |
while childpos < endpos: |
| 303 |
|
| 304 |
rightpos = childpos + 1 |
| 305 |
if rightpos < endpos and not heap[rightpos] < heap[childpos]: |
| 306 |
childpos = rightpos |
| 307 |
|
| 308 |
heap[pos] = heap[childpos] |
| 309 |
pos = childpos |
| 310 |
childpos = 2*pos + 1 |
| 311 |
|
| 312 |
|
| 313 |
heap[pos] = newitem |
| 314 |
_siftdown_max(heap, startpos, pos) |
| 315 |
|
| 316 |
|
| 317 |
|
| 318 |
class _MergeNode: |
| 319 |
""" |
| 320 |
Binary tree invariants: |
| 321 |
- A node N is a leaf iff N.leaf is N |
| 322 |
- For each leaf node: |
| 323 |
- leaf.right is an iterator |
| 324 |
- leaf.left is the item most recently produced by leaf.right |
| 325 |
- leaf.key is key(leaf.left) |
| 326 |
- For each non-leaf node: |
| 327 |
- node.left and node.right are Nodes |
| 328 |
- node.left.parent is node is node.right.parent |
| 329 |
- node.leaf is one of node's descendant leaves |
| 330 |
- node.key is node.leaf.key |
| 331 |
- if "winner" is the higher priority of node.left and |
| 332 |
node.right based on their keys, then node.leaf is |
| 333 |
winner.leaf and node.key is winner.key. |
| 334 |
""" |
| 335 |
|
| 336 |
__slots__ = "key", "leaf", "parent", "left", "right" |
| 337 |
|
| 338 |
@classmethod |
| 339 |
def construct_leaf(cls, iterator, keyfunc): |
| 340 |
it = iter(iterator) |
| 341 |
try: |
| 342 |
item = next(it) |
| 343 |
except StopIteration: |
| 344 |
return None |
| 345 |
key = item if keyfunc is None else keyfunc(item) |
| 346 |
node = cls() |
| 347 |
node.key = key |
| 348 |
node.left = item |
| 349 |
node.right = it |
| 350 |
node.parent = None |
| 351 |
node.leaf = node |
| 352 |
return node |
| 353 |
|
| 354 |
@classmethod |
| 355 |
def construct_parent(cls, left, right, reverse): |
| 356 |
if reverse: |
| 357 |
winner = right if left.key < right.key else left |
| 358 |
else: |
| 359 |
winner = right if right.key < left.key else left |
| 360 |
node = cls() |
| 361 |
node.key = winner.key |
| 362 |
node.left = left |
| 363 |
node.right = right |
| 364 |
node.parent = None |
| 365 |
node.leaf = winner.leaf |
| 366 |
left.parent = right.parent = node |
| 367 |
return node |
| 368 |
|
| 369 |
@classmethod |
| 370 |
def build_tree(cls, iterables, key, reverse): |
| 371 |
nodes = [] |
| 372 |
for it in iterables: |
| 373 |
leaf = cls.construct_leaf(it, key) |
| 374 |
if leaf is not None: |
| 375 |
nodes.append(leaf) |
| 376 |
if not nodes: |
| 377 |
return None |
| 378 |
n = len(nodes) |
| 379 |
|
| 380 |
|
| 381 |
while n > 1: |
| 382 |
|
| 383 |
|
| 384 |
new_nodes, rest = nodes[:n & 1], nodes[n & 1:] |
| 385 |
for left, right in zip(rest[::2], rest[1::2]): |
| 386 |
parent = cls.construct_parent(left, right, reverse) |
| 387 |
new_nodes.append(parent) |
| 388 |
nodes = new_nodes |
| 389 |
n = len(nodes) |
| 390 |
(root,) = nodes |
| 391 |
return root |
| 392 |
|
| 393 |
def promote_sibling(self): |
| 394 |
""" |
| 395 |
Remove self and its sibling from the tree, while linking their |
| 396 |
parent to the sibling's children. |
| 397 |
""" |
| 398 |
assert self.leaf is self |
| 399 |
parent = self.parent |
| 400 |
left = parent.left |
| 401 |
right = parent.right |
| 402 |
sibling = left if self is right else right |
| 403 |
parent.left = sibling.left |
| 404 |
parent.right = sibling.right |
| 405 |
parent.key = sibling.key |
| 406 |
if sibling.leaf is sibling: |
| 407 |
|
| 408 |
parent.leaf = parent |
| 409 |
else: |
| 410 |
parent.leaf = sibling.leaf |
| 411 |
|
| 412 |
sibling.left.parent = sibling.right.parent = parent |
| 413 |
return parent |
| 414 |
|
| 415 |
|
| 416 |
def merge(*iterables, key=None, reverse=False): |
| 417 |
'''Merge multiple sorted inputs into a single sorted output. |
| 418 |
|
| 419 |
Similar to sorted(itertools.chain(*iterables)) but returns a generator, |
| 420 |
does not pull the data into memory all at once, and assumes that each of |
| 421 |
the input streams is already sorted (smallest to largest). |
| 422 |
|
| 423 |
>>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25])) |
| 424 |
[0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25] |
| 425 |
|
| 426 |
If *key* is not None, applies a key function to each element to determine |
| 427 |
its sort order. |
| 428 |
|
| 429 |
>>> list(merge(['dog', 'horse'], ['cat', 'fish', 'kangaroo'], key=len)) |
| 430 |
['dog', 'cat', 'fish', 'horse', 'kangaroo'] |
| 431 |
|
| 432 |
''' |
| 433 |
|
| 434 |
root = _MergeNode.build_tree(iterables, key, reverse) |
| 435 |
if root is None: |
| 436 |
return |
| 437 |
elif root.leaf is root: |
| 438 |
yield root.left |
| 439 |
yield from root.right |
| 440 |
return |
| 441 |
|
| 442 |
_next, _StopIteration = next, StopIteration |
| 443 |
while True: |
| 444 |
|
| 445 |
|
| 446 |
node = root.leaf |
| 447 |
yield node.left |
| 448 |
|
| 449 |
|
| 450 |
try: |
| 451 |
node.left = val = _next(node.right) |
| 452 |
except _StopIteration: |
| 453 |
node = node.promote_sibling() |
| 454 |
if root.leaf is root: |
| 455 |
yield root.left |
| 456 |
yield from root.right |
| 457 |
return |
| 458 |
else: |
| 459 |
node.key = val if key is None else key(val) |
| 460 |
|
| 461 |
|
| 462 |
|
| 463 |
|
| 464 |
if reverse: |
| 465 |
while node is not root: |
| 466 |
node = node.parent |
| 467 |
left, right = node.left, node.right |
| 468 |
winner = right if left.key < right.key else left |
| 469 |
node.key = winner.key |
| 470 |
node.leaf = winner.leaf |
| 471 |
else: |
| 472 |
while node is not root: |
| 473 |
node = node.parent |
| 474 |
left, right = node.left, node.right |
| 475 |
winner = right if right.key < left.key else left |
| 476 |
node.key = winner.key |
| 477 |
node.leaf = winner.leaf |
| 478 |
|
| 479 |
|
| 480 |
|
| 481 |
|
| 482 |
|
| 483 |
|
| 484 |
|
| 485 |
|
| 486 |
|
| 487 |
|
| 488 |
|
| 489 |
|
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
|
| 494 |
|
| 495 |
|
| 496 |
|
| 497 |
|
| 498 |
|
| 499 |
|
| 500 |
|
| 501 |
|
| 502 |
|
| 503 |
|
| 504 |
|
| 505 |
|
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
|
| 510 |
|
| 511 |
|
| 512 |
|
| 513 |
|
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
|
| 522 |
|
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
|
| 527 |
|
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
|
| 536 |
|
| 537 |
|
| 538 |
|
| 539 |
|
| 540 |
|
| 541 |
|
| 542 |
|
| 543 |
|
| 544 |
|
| 545 |
|
| 546 |
|
| 547 |
def nsmallest(n, iterable, key=None): |
| 548 |
"""Find the n smallest elements in a dataset. |
| 549 |
|
| 550 |
Equivalent to: sorted(iterable, key=key)[:n] |
| 551 |
""" |
| 552 |
|
| 553 |
|
| 554 |
if n == 1: |
| 555 |
it = iter(iterable) |
| 556 |
sentinel = object() |
| 557 |
result = min(it, default=sentinel, key=key) |
| 558 |
return [] if result is sentinel else [result] |
| 559 |
|
| 560 |
|
| 561 |
try: |
| 562 |
size = len(iterable) |
| 563 |
except (TypeError, AttributeError): |
| 564 |
pass |
| 565 |
else: |
| 566 |
if n >= size: |
| 567 |
return sorted(iterable, key=key)[:n] |
| 568 |
|
| 569 |
|
| 570 |
if key is None: |
| 571 |
it = iter(iterable) |
| 572 |
|
| 573 |
|
| 574 |
result = [(elem, i) for i, elem in zip(range(n), it)] |
| 575 |
if not result: |
| 576 |
return result |
| 577 |
_heapify_max(result) |
| 578 |
top = result[0][0] |
| 579 |
order = n |
| 580 |
_heapreplace = _heapreplace_max |
| 581 |
for elem in it: |
| 582 |
if elem < top: |
| 583 |
_heapreplace(result, (elem, order)) |
| 584 |
top, _order = result[0] |
| 585 |
order += 1 |
| 586 |
result.sort() |
| 587 |
return [elem for (elem, order) in result] |
| 588 |
|
| 589 |
|
| 590 |
it = iter(iterable) |
| 591 |
result = [(key(elem), i, elem) for i, elem in zip(range(n), it)] |
| 592 |
if not result: |
| 593 |
return result |
| 594 |
_heapify_max(result) |
| 595 |
top = result[0][0] |
| 596 |
order = n |
| 597 |
_heapreplace = _heapreplace_max |
| 598 |
for elem in it: |
| 599 |
k = key(elem) |
| 600 |
if k < top: |
| 601 |
_heapreplace(result, (k, order, elem)) |
| 602 |
top, _order, _elem = result[0] |
| 603 |
order += 1 |
| 604 |
result.sort() |
| 605 |
return [elem for (k, order, elem) in result] |
| 606 |
|
| 607 |
def nlargest(n, iterable, key=None): |
| 608 |
"""Find the n largest elements in a dataset. |
| 609 |
|
| 610 |
Equivalent to: sorted(iterable, key=key, reverse=True)[:n] |
| 611 |
""" |
| 612 |
|
| 613 |
|
| 614 |
if n == 1: |
| 615 |
it = iter(iterable) |
| 616 |
sentinel = object() |
| 617 |
result = max(it, default=sentinel, key=key) |
| 618 |
return [] if result is sentinel else [result] |
| 619 |
|
| 620 |
|
| 621 |
try: |
| 622 |
size = len(iterable) |
| 623 |
except (TypeError, AttributeError): |
| 624 |
pass |
| 625 |
else: |
| 626 |
if n >= size: |
| 627 |
return sorted(iterable, key=key, reverse=True)[:n] |
| 628 |
|
| 629 |
|
| 630 |
if key is None: |
| 631 |
it = iter(iterable) |
| 632 |
result = [(elem, i) for i, elem in zip(range(0, -n, -1), it)] |
| 633 |
if not result: |
| 634 |
return result |
| 635 |
heapify(result) |
| 636 |
top = result[0][0] |
| 637 |
order = -n |
| 638 |
_heapreplace = heapreplace |
| 639 |
for elem in it: |
| 640 |
if top < elem: |
| 641 |
_heapreplace(result, (elem, order)) |
| 642 |
top, _order = result[0] |
| 643 |
order -= 1 |
| 644 |
result.sort(reverse=True) |
| 645 |
return [elem for (elem, order) in result] |
| 646 |
|
| 647 |
|
| 648 |
it = iter(iterable) |
| 649 |
result = [(key(elem), i, elem) for i, elem in zip(range(0, -n, -1), it)] |
| 650 |
if not result: |
| 651 |
return result |
| 652 |
heapify(result) |
| 653 |
top = result[0][0] |
| 654 |
order = -n |
| 655 |
_heapreplace = heapreplace |
| 656 |
for elem in it: |
| 657 |
k = key(elem) |
| 658 |
if top < k: |
| 659 |
_heapreplace(result, (k, order, elem)) |
| 660 |
top, _order, _elem = result[0] |
| 661 |
order -= 1 |
| 662 |
result.sort(reverse=True) |
| 663 |
return [elem for (k, order, elem) in result] |
| 664 |
|
| 665 |
|
| 666 |
try: |
| 667 |
from _heapq import * |
| 668 |
except ImportError: |
| 669 |
pass |
| 670 |
try: |
| 671 |
from _heapq import _heapreplace_max |
| 672 |
except ImportError: |
| 673 |
pass |
| 674 |
try: |
| 675 |
from _heapq import _heapify_max |
| 676 |
except ImportError: |
| 677 |
pass |
| 678 |
try: |
| 679 |
from _heapq import _heappop_max |
| 680 |
except ImportError: |
| 681 |
pass |
| 682 |
|
| 683 |
|
| 684 |
if __name__ == "__main__": |
| 685 |
|
| 686 |
import doctest |
| 687 |
print(doctest.testmod()) |