Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ExeBy/smexe_ro.../lib64/python2....
File: heapq.py
# -*- coding: latin-1 -*-
[0] Fix | Delete
[1] Fix | Delete
"""Heap queue algorithm (a.k.a. priority queue).
[2] Fix | Delete
[3] Fix | Delete
Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
[4] Fix | Delete
all k, counting elements from 0. For the sake of comparison,
[5] Fix | Delete
non-existing elements are considered to be infinite. The interesting
[6] Fix | Delete
property of a heap is that a[0] is always its smallest element.
[7] Fix | Delete
[8] Fix | Delete
Usage:
[9] Fix | Delete
[10] Fix | Delete
heap = [] # creates an empty heap
[11] Fix | Delete
heappush(heap, item) # pushes a new item on the heap
[12] Fix | Delete
item = heappop(heap) # pops the smallest item from the heap
[13] Fix | Delete
item = heap[0] # smallest item on the heap without popping it
[14] Fix | Delete
heapify(x) # transforms list into a heap, in-place, in linear time
[15] Fix | Delete
item = heapreplace(heap, item) # pops and returns smallest item, and adds
[16] Fix | Delete
# new item; the heap size is unchanged
[17] Fix | Delete
[18] Fix | Delete
Our API differs from textbook heap algorithms as follows:
[19] Fix | Delete
[20] Fix | Delete
- We use 0-based indexing. This makes the relationship between the
[21] Fix | Delete
index for a node and the indexes for its children slightly less
[22] Fix | Delete
obvious, but is more suitable since Python uses 0-based indexing.
[23] Fix | Delete
[24] Fix | Delete
- Our heappop() method returns the smallest item, not the largest.
[25] Fix | Delete
[26] Fix | Delete
These two make it possible to view the heap as a regular Python list
[27] Fix | Delete
without surprises: heap[0] is the smallest item, and heap.sort()
[28] Fix | Delete
maintains the heap invariant!
[29] Fix | Delete
"""
[30] Fix | Delete
[31] Fix | Delete
# Original code by Kevin O'Connor, augmented by Tim Peters and Raymond Hettinger
[32] Fix | Delete
[33] Fix | Delete
__about__ = """Heap queues
[34] Fix | Delete
[35] Fix | Delete
[36] Fix | Delete
[37] Fix | Delete
Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
[38] Fix | Delete
all k, counting elements from 0. For the sake of comparison,
[39] Fix | Delete
non-existing elements are considered to be infinite. The interesting
[40] Fix | Delete
property of a heap is that a[0] is always its smallest element.
[41] Fix | Delete
[42] Fix | Delete
The strange invariant above is meant to be an efficient memory
[43] Fix | Delete
representation for a tournament. The numbers below are `k', not a[k]:
[44] Fix | Delete
[45] Fix | Delete
0
[46] Fix | Delete
[47] Fix | Delete
1 2
[48] Fix | Delete
[49] Fix | Delete
3 4 5 6
[50] Fix | Delete
[51] Fix | Delete
7 8 9 10 11 12 13 14
[52] Fix | Delete
[53] Fix | Delete
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
[54] Fix | Delete
[55] Fix | Delete
[56] Fix | Delete
In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'. In
[57] Fix | Delete
a usual binary tournament we see in sports, each cell is the winner
[58] Fix | Delete
over the two cells it tops, and we can trace the winner down the tree
[59] Fix | Delete
to see all opponents s/he had. However, in many computer applications
[60] Fix | Delete
of such tournaments, we do not need to trace the history of a winner.
[61] Fix | Delete
To be more memory efficient, when a winner is promoted, we try to
[62] Fix | Delete
replace it by something else at a lower level, and the rule becomes
[63] Fix | Delete
that a cell and the two cells it tops contain three different items,
[64] Fix | Delete
but the top cell "wins" over the two topped cells.
[65] Fix | Delete
[66] Fix | Delete
If this heap invariant is protected at all time, index 0 is clearly
[67] Fix | Delete
the overall winner. The simplest algorithmic way to remove it and
[68] Fix | Delete
find the "next" winner is to move some loser (let's say cell 30 in the
[69] Fix | Delete
diagram above) into the 0 position, and then percolate this new 0 down
[70] Fix | Delete
the tree, exchanging values, until the invariant is re-established.
[71] Fix | Delete
This is clearly logarithmic on the total number of items in the tree.
[72] Fix | Delete
By iterating over all items, you get an O(n ln n) sort.
[73] Fix | Delete
[74] Fix | Delete
A nice feature of this sort is that you can efficiently insert new
[75] Fix | Delete
items while the sort is going on, provided that the inserted items are
[76] Fix | Delete
not "better" than the last 0'th element you extracted. This is
[77] Fix | Delete
especially useful in simulation contexts, where the tree holds all
[78] Fix | Delete
incoming events, and the "win" condition means the smallest scheduled
[79] Fix | Delete
time. When an event schedule other events for execution, they are
[80] Fix | Delete
scheduled into the future, so they can easily go into the heap. So, a
[81] Fix | Delete
heap is a good structure for implementing schedulers (this is what I
[82] Fix | Delete
used for my MIDI sequencer :-).
[83] Fix | Delete
[84] Fix | Delete
Various structures for implementing schedulers have been extensively
[85] Fix | Delete
studied, and heaps are good for this, as they are reasonably speedy,
[86] Fix | Delete
the speed is almost constant, and the worst case is not much different
[87] Fix | Delete
than the average case. However, there are other representations which
[88] Fix | Delete
are more efficient overall, yet the worst cases might be terrible.
[89] Fix | Delete
[90] Fix | Delete
Heaps are also very useful in big disk sorts. You most probably all
[91] Fix | Delete
know that a big sort implies producing "runs" (which are pre-sorted
[92] Fix | Delete
sequences, which size is usually related to the amount of CPU memory),
[93] Fix | Delete
followed by a merging passes for these runs, which merging is often
[94] Fix | Delete
very cleverly organised[1]. It is very important that the initial
[95] Fix | Delete
sort produces the longest runs possible. Tournaments are a good way
[96] Fix | Delete
to that. If, using all the memory available to hold a tournament, you
[97] Fix | Delete
replace and percolate items that happen to fit the current run, you'll
[98] Fix | Delete
produce runs which are twice the size of the memory for random input,
[99] Fix | Delete
and much better for input fuzzily ordered.
[100] Fix | Delete
[101] Fix | Delete
Moreover, if you output the 0'th item on disk and get an input which
[102] Fix | Delete
may not fit in the current tournament (because the value "wins" over
[103] Fix | Delete
the last output value), it cannot fit in the heap, so the size of the
[104] Fix | Delete
heap decreases. The freed memory could be cleverly reused immediately
[105] Fix | Delete
for progressively building a second heap, which grows at exactly the
[106] Fix | Delete
same rate the first heap is melting. When the first heap completely
[107] Fix | Delete
vanishes, you switch heaps and start a new run. Clever and quite
[108] Fix | Delete
effective!
[109] Fix | Delete
[110] Fix | Delete
In a word, heaps are useful memory structures to know. I use them in
[111] Fix | Delete
a few applications, and I think it is good to keep a `heap' module
[112] Fix | Delete
around. :-)
[113] Fix | Delete
[114] Fix | Delete
--------------------
[115] Fix | Delete
[1] The disk balancing algorithms which are current, nowadays, are
[116] Fix | Delete
more annoying than clever, and this is a consequence of the seeking
[117] Fix | Delete
capabilities of the disks. On devices which cannot seek, like big
[118] Fix | Delete
tape drives, the story was quite different, and one had to be very
[119] Fix | Delete
clever to ensure (far in advance) that each tape movement will be the
[120] Fix | Delete
most effective possible (that is, will best participate at
[121] Fix | Delete
"progressing" the merge). Some tapes were even able to read
[122] Fix | Delete
backwards, and this was also used to avoid the rewinding time.
[123] Fix | Delete
Believe me, real good tape sorts were quite spectacular to watch!
[124] Fix | Delete
From all times, sorting has always been a Great Art! :-)
[125] Fix | Delete
"""
[126] Fix | Delete
[127] Fix | Delete
__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge',
[128] Fix | Delete
'nlargest', 'nsmallest', 'heappushpop']
[129] Fix | Delete
[130] Fix | Delete
from itertools import islice, count, imap, izip, tee, chain
[131] Fix | Delete
from operator import itemgetter
[132] Fix | Delete
[133] Fix | Delete
def cmp_lt(x, y):
[134] Fix | Delete
# Use __lt__ if available; otherwise, try __le__.
[135] Fix | Delete
# In Py3.x, only __lt__ will be called.
[136] Fix | Delete
return (x < y) if hasattr(x, '__lt__') else (not y <= x)
[137] Fix | Delete
[138] Fix | Delete
def heappush(heap, item):
[139] Fix | Delete
"""Push item onto heap, maintaining the heap invariant."""
[140] Fix | Delete
heap.append(item)
[141] Fix | Delete
_siftdown(heap, 0, len(heap)-1)
[142] Fix | Delete
[143] Fix | Delete
def heappop(heap):
[144] Fix | Delete
"""Pop the smallest item off the heap, maintaining the heap invariant."""
[145] Fix | Delete
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
[146] Fix | Delete
if heap:
[147] Fix | Delete
returnitem = heap[0]
[148] Fix | Delete
heap[0] = lastelt
[149] Fix | Delete
_siftup(heap, 0)
[150] Fix | Delete
else:
[151] Fix | Delete
returnitem = lastelt
[152] Fix | Delete
return returnitem
[153] Fix | Delete
[154] Fix | Delete
def heapreplace(heap, item):
[155] Fix | Delete
"""Pop and return the current smallest value, and add the new item.
[156] Fix | Delete
[157] Fix | Delete
This is more efficient than heappop() followed by heappush(), and can be
[158] Fix | Delete
more appropriate when using a fixed-size heap. Note that the value
[159] Fix | Delete
returned may be larger than item! That constrains reasonable uses of
[160] Fix | Delete
this routine unless written as part of a conditional replacement:
[161] Fix | Delete
[162] Fix | Delete
if item > heap[0]:
[163] Fix | Delete
item = heapreplace(heap, item)
[164] Fix | Delete
"""
[165] Fix | Delete
returnitem = heap[0] # raises appropriate IndexError if heap is empty
[166] Fix | Delete
heap[0] = item
[167] Fix | Delete
_siftup(heap, 0)
[168] Fix | Delete
return returnitem
[169] Fix | Delete
[170] Fix | Delete
def heappushpop(heap, item):
[171] Fix | Delete
"""Fast version of a heappush followed by a heappop."""
[172] Fix | Delete
if heap and cmp_lt(heap[0], item):
[173] Fix | Delete
item, heap[0] = heap[0], item
[174] Fix | Delete
_siftup(heap, 0)
[175] Fix | Delete
return item
[176] Fix | Delete
[177] Fix | Delete
def heapify(x):
[178] Fix | Delete
"""Transform list into a heap, in-place, in O(len(x)) time."""
[179] Fix | Delete
n = len(x)
[180] Fix | Delete
# Transform bottom-up. The largest index there's any point to looking at
[181] Fix | Delete
# is the largest with a child index in-range, so must have 2*i + 1 < n,
[182] Fix | Delete
# or i < (n-1)/2. If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so
[183] Fix | Delete
# j-1 is the largest, which is n//2 - 1. If n is odd = 2*j+1, this is
[184] Fix | Delete
# (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1.
[185] Fix | Delete
for i in reversed(xrange(n//2)):
[186] Fix | Delete
_siftup(x, i)
[187] Fix | Delete
[188] Fix | Delete
def _heappushpop_max(heap, item):
[189] Fix | Delete
"""Maxheap version of a heappush followed by a heappop."""
[190] Fix | Delete
if heap and cmp_lt(item, heap[0]):
[191] Fix | Delete
item, heap[0] = heap[0], item
[192] Fix | Delete
_siftup_max(heap, 0)
[193] Fix | Delete
return item
[194] Fix | Delete
[195] Fix | Delete
def _heapify_max(x):
[196] Fix | Delete
"""Transform list into a maxheap, in-place, in O(len(x)) time."""
[197] Fix | Delete
n = len(x)
[198] Fix | Delete
for i in reversed(range(n//2)):
[199] Fix | Delete
_siftup_max(x, i)
[200] Fix | Delete
[201] Fix | Delete
def nlargest(n, iterable):
[202] Fix | Delete
"""Find the n largest elements in a dataset.
[203] Fix | Delete
[204] Fix | Delete
Equivalent to: sorted(iterable, reverse=True)[:n]
[205] Fix | Delete
"""
[206] Fix | Delete
if n < 0:
[207] Fix | Delete
return []
[208] Fix | Delete
it = iter(iterable)
[209] Fix | Delete
result = list(islice(it, n))
[210] Fix | Delete
if not result:
[211] Fix | Delete
return result
[212] Fix | Delete
heapify(result)
[213] Fix | Delete
_heappushpop = heappushpop
[214] Fix | Delete
for elem in it:
[215] Fix | Delete
_heappushpop(result, elem)
[216] Fix | Delete
result.sort(reverse=True)
[217] Fix | Delete
return result
[218] Fix | Delete
[219] Fix | Delete
def nsmallest(n, iterable):
[220] Fix | Delete
"""Find the n smallest elements in a dataset.
[221] Fix | Delete
[222] Fix | Delete
Equivalent to: sorted(iterable)[:n]
[223] Fix | Delete
"""
[224] Fix | Delete
if n < 0:
[225] Fix | Delete
return []
[226] Fix | Delete
it = iter(iterable)
[227] Fix | Delete
result = list(islice(it, n))
[228] Fix | Delete
if not result:
[229] Fix | Delete
return result
[230] Fix | Delete
_heapify_max(result)
[231] Fix | Delete
_heappushpop = _heappushpop_max
[232] Fix | Delete
for elem in it:
[233] Fix | Delete
_heappushpop(result, elem)
[234] Fix | Delete
result.sort()
[235] Fix | Delete
return result
[236] Fix | Delete
[237] Fix | Delete
# 'heap' is a heap at all indices >= startpos, except possibly for pos. pos
[238] Fix | Delete
# is the index of a leaf with a possibly out-of-order value. Restore the
[239] Fix | Delete
# heap invariant.
[240] Fix | Delete
def _siftdown(heap, startpos, pos):
[241] Fix | Delete
newitem = heap[pos]
[242] Fix | Delete
# Follow the path to the root, moving parents down until finding a place
[243] Fix | Delete
# newitem fits.
[244] Fix | Delete
while pos > startpos:
[245] Fix | Delete
parentpos = (pos - 1) >> 1
[246] Fix | Delete
parent = heap[parentpos]
[247] Fix | Delete
if cmp_lt(newitem, parent):
[248] Fix | Delete
heap[pos] = parent
[249] Fix | Delete
pos = parentpos
[250] Fix | Delete
continue
[251] Fix | Delete
break
[252] Fix | Delete
heap[pos] = newitem
[253] Fix | Delete
[254] Fix | Delete
# The child indices of heap index pos are already heaps, and we want to make
[255] Fix | Delete
# a heap at index pos too. We do this by bubbling the smaller child of
[256] Fix | Delete
# pos up (and so on with that child's children, etc) until hitting a leaf,
[257] Fix | Delete
# then using _siftdown to move the oddball originally at index pos into place.
[258] Fix | Delete
#
[259] Fix | Delete
# We *could* break out of the loop as soon as we find a pos where newitem <=
[260] Fix | Delete
# both its children, but turns out that's not a good idea, and despite that
[261] Fix | Delete
# many books write the algorithm that way. During a heap pop, the last array
[262] Fix | Delete
# element is sifted in, and that tends to be large, so that comparing it
[263] Fix | Delete
# against values starting from the root usually doesn't pay (= usually doesn't
[264] Fix | Delete
# get us out of the loop early). See Knuth, Volume 3, where this is
[265] Fix | Delete
# explained and quantified in an exercise.
[266] Fix | Delete
#
[267] Fix | Delete
# Cutting the # of comparisons is important, since these routines have no
[268] Fix | Delete
# way to extract "the priority" from an array element, so that intelligence
[269] Fix | Delete
# is likely to be hiding in custom __cmp__ methods, or in array elements
[270] Fix | Delete
# storing (priority, record) tuples. Comparisons are thus potentially
[271] Fix | Delete
# expensive.
[272] Fix | Delete
#
[273] Fix | Delete
# On random arrays of length 1000, making this change cut the number of
[274] Fix | Delete
# comparisons made by heapify() a little, and those made by exhaustive
[275] Fix | Delete
# heappop() a lot, in accord with theory. Here are typical results from 3
[276] Fix | Delete
# runs (3 just to demonstrate how small the variance is):
[277] Fix | Delete
#
[278] Fix | Delete
# Compares needed by heapify Compares needed by 1000 heappops
[279] Fix | Delete
# -------------------------- --------------------------------
[280] Fix | Delete
# 1837 cut to 1663 14996 cut to 8680
[281] Fix | Delete
# 1855 cut to 1659 14966 cut to 8678
[282] Fix | Delete
# 1847 cut to 1660 15024 cut to 8703
[283] Fix | Delete
#
[284] Fix | Delete
# Building the heap by using heappush() 1000 times instead required
[285] Fix | Delete
# 2198, 2148, and 2219 compares: heapify() is more efficient, when
[286] Fix | Delete
# you can use it.
[287] Fix | Delete
#
[288] Fix | Delete
# The total compares needed by list.sort() on the same lists were 8627,
[289] Fix | Delete
# 8627, and 8632 (this should be compared to the sum of heapify() and
[290] Fix | Delete
# heappop() compares): list.sort() is (unsurprisingly!) more efficient
[291] Fix | Delete
# for sorting.
[292] Fix | Delete
[293] Fix | Delete
def _siftup(heap, pos):
[294] Fix | Delete
endpos = len(heap)
[295] Fix | Delete
startpos = pos
[296] Fix | Delete
newitem = heap[pos]
[297] Fix | Delete
# Bubble up the smaller child until hitting a leaf.
[298] Fix | Delete
childpos = 2*pos + 1 # leftmost child position
[299] Fix | Delete
while childpos < endpos:
[300] Fix | Delete
# Set childpos to index of smaller child.
[301] Fix | Delete
rightpos = childpos + 1
[302] Fix | Delete
if rightpos < endpos and not cmp_lt(heap[childpos], heap[rightpos]):
[303] Fix | Delete
childpos = rightpos
[304] Fix | Delete
# Move the smaller child up.
[305] Fix | Delete
heap[pos] = heap[childpos]
[306] Fix | Delete
pos = childpos
[307] Fix | Delete
childpos = 2*pos + 1
[308] Fix | Delete
# The leaf at pos is empty now. Put newitem there, and bubble it up
[309] Fix | Delete
# to its final resting place (by sifting its parents down).
[310] Fix | Delete
heap[pos] = newitem
[311] Fix | Delete
_siftdown(heap, startpos, pos)
[312] Fix | Delete
[313] Fix | Delete
def _siftdown_max(heap, startpos, pos):
[314] Fix | Delete
'Maxheap variant of _siftdown'
[315] Fix | Delete
newitem = heap[pos]
[316] Fix | Delete
# Follow the path to the root, moving parents down until finding a place
[317] Fix | Delete
# newitem fits.
[318] Fix | Delete
while pos > startpos:
[319] Fix | Delete
parentpos = (pos - 1) >> 1
[320] Fix | Delete
parent = heap[parentpos]
[321] Fix | Delete
if cmp_lt(parent, newitem):
[322] Fix | Delete
heap[pos] = parent
[323] Fix | Delete
pos = parentpos
[324] Fix | Delete
continue
[325] Fix | Delete
break
[326] Fix | Delete
heap[pos] = newitem
[327] Fix | Delete
[328] Fix | Delete
def _siftup_max(heap, pos):
[329] Fix | Delete
'Maxheap variant of _siftup'
[330] Fix | Delete
endpos = len(heap)
[331] Fix | Delete
startpos = pos
[332] Fix | Delete
newitem = heap[pos]
[333] Fix | Delete
# Bubble up the larger child until hitting a leaf.
[334] Fix | Delete
childpos = 2*pos + 1 # leftmost child position
[335] Fix | Delete
while childpos < endpos:
[336] Fix | Delete
# Set childpos to index of larger child.
[337] Fix | Delete
rightpos = childpos + 1
[338] Fix | Delete
if rightpos < endpos and not cmp_lt(heap[rightpos], heap[childpos]):
[339] Fix | Delete
childpos = rightpos
[340] Fix | Delete
# Move the larger child up.
[341] Fix | Delete
heap[pos] = heap[childpos]
[342] Fix | Delete
pos = childpos
[343] Fix | Delete
childpos = 2*pos + 1
[344] Fix | Delete
# The leaf at pos is empty now. Put newitem there, and bubble it up
[345] Fix | Delete
# to its final resting place (by sifting its parents down).
[346] Fix | Delete
heap[pos] = newitem
[347] Fix | Delete
_siftdown_max(heap, startpos, pos)
[348] Fix | Delete
[349] Fix | Delete
# If available, use C implementation
[350] Fix | Delete
try:
[351] Fix | Delete
from _heapq import *
[352] Fix | Delete
except ImportError:
[353] Fix | Delete
pass
[354] Fix | Delete
[355] Fix | Delete
def merge(*iterables):
[356] Fix | Delete
'''Merge multiple sorted inputs into a single sorted output.
[357] Fix | Delete
[358] Fix | Delete
Similar to sorted(itertools.chain(*iterables)) but returns a generator,
[359] Fix | Delete
does not pull the data into memory all at once, and assumes that each of
[360] Fix | Delete
the input streams is already sorted (smallest to largest).
[361] Fix | Delete
[362] Fix | Delete
>>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))
[363] Fix | Delete
[0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]
[364] Fix | Delete
[365] Fix | Delete
'''
[366] Fix | Delete
_heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration
[367] Fix | Delete
_len = len
[368] Fix | Delete
[369] Fix | Delete
h = []
[370] Fix | Delete
h_append = h.append
[371] Fix | Delete
for itnum, it in enumerate(map(iter, iterables)):
[372] Fix | Delete
try:
[373] Fix | Delete
next = it.next
[374] Fix | Delete
h_append([next(), itnum, next])
[375] Fix | Delete
except _StopIteration:
[376] Fix | Delete
pass
[377] Fix | Delete
heapify(h)
[378] Fix | Delete
[379] Fix | Delete
while _len(h) > 1:
[380] Fix | Delete
try:
[381] Fix | Delete
while 1:
[382] Fix | Delete
v, itnum, next = s = h[0]
[383] Fix | Delete
yield v
[384] Fix | Delete
s[0] = next() # raises StopIteration when exhausted
[385] Fix | Delete
_heapreplace(h, s) # restore heap condition
[386] Fix | Delete
except _StopIteration:
[387] Fix | Delete
_heappop(h) # remove empty iterator
[388] Fix | Delete
if h:
[389] Fix | Delete
# fast case when only a single iterator remains
[390] Fix | Delete
v, itnum, next = h[0]
[391] Fix | Delete
yield v
[392] Fix | Delete
for v in next.__self__:
[393] Fix | Delete
yield v
[394] Fix | Delete
[395] Fix | Delete
# Extend the implementations of nsmallest and nlargest to use a key= argument
[396] Fix | Delete
_nsmallest = nsmallest
[397] Fix | Delete
def nsmallest(n, iterable, key=None):
[398] Fix | Delete
"""Find the n smallest elements in a dataset.
[399] Fix | Delete
[400] Fix | Delete
Equivalent to: sorted(iterable, key=key)[:n]
[401] Fix | Delete
"""
[402] Fix | Delete
# Short-cut for n==1 is to use min() when len(iterable)>0
[403] Fix | Delete
if n == 1:
[404] Fix | Delete
it = iter(iterable)
[405] Fix | Delete
head = list(islice(it, 1))
[406] Fix | Delete
if not head:
[407] Fix | Delete
return []
[408] Fix | Delete
if key is None:
[409] Fix | Delete
return [min(chain(head, it))]
[410] Fix | Delete
return [min(chain(head, it), key=key)]
[411] Fix | Delete
[412] Fix | Delete
# When n>=size, it's faster to use sorted()
[413] Fix | Delete
try:
[414] Fix | Delete
size = len(iterable)
[415] Fix | Delete
except (TypeError, AttributeError):
[416] Fix | Delete
pass
[417] Fix | Delete
else:
[418] Fix | Delete
if n >= size:
[419] Fix | Delete
return sorted(iterable, key=key)[:n]
[420] Fix | Delete
[421] Fix | Delete
# When key is none, use simpler decoration
[422] Fix | Delete
if key is None:
[423] Fix | Delete
it = izip(iterable, count()) # decorate
[424] Fix | Delete
result = _nsmallest(n, it)
[425] Fix | Delete
return map(itemgetter(0), result) # undecorate
[426] Fix | Delete
[427] Fix | Delete
# General case, slowest method
[428] Fix | Delete
in1, in2 = tee(iterable)
[429] Fix | Delete
it = izip(imap(key, in1), count(), in2) # decorate
[430] Fix | Delete
result = _nsmallest(n, it)
[431] Fix | Delete
return map(itemgetter(2), result) # undecorate
[432] Fix | Delete
[433] Fix | Delete
_nlargest = nlargest
[434] Fix | Delete
def nlargest(n, iterable, key=None):
[435] Fix | Delete
"""Find the n largest elements in a dataset.
[436] Fix | Delete
[437] Fix | Delete
Equivalent to: sorted(iterable, key=key, reverse=True)[:n]
[438] Fix | Delete
"""
[439] Fix | Delete
[440] Fix | Delete
# Short-cut for n==1 is to use max() when len(iterable)>0
[441] Fix | Delete
if n == 1:
[442] Fix | Delete
it = iter(iterable)
[443] Fix | Delete
head = list(islice(it, 1))
[444] Fix | Delete
if not head:
[445] Fix | Delete
return []
[446] Fix | Delete
if key is None:
[447] Fix | Delete
return [max(chain(head, it))]
[448] Fix | Delete
return [max(chain(head, it), key=key)]
[449] Fix | Delete
[450] Fix | Delete
# When n>=size, it's faster to use sorted()
[451] Fix | Delete
try:
[452] Fix | Delete
size = len(iterable)
[453] Fix | Delete
except (TypeError, AttributeError):
[454] Fix | Delete
pass
[455] Fix | Delete
else:
[456] Fix | Delete
if n >= size:
[457] Fix | Delete
return sorted(iterable, key=key, reverse=True)[:n]
[458] Fix | Delete
[459] Fix | Delete
# When key is none, use simpler decoration
[460] Fix | Delete
if key is None:
[461] Fix | Delete
it = izip(iterable, count(0,-1)) # decorate
[462] Fix | Delete
result = _nlargest(n, it)
[463] Fix | Delete
return map(itemgetter(0), result) # undecorate
[464] Fix | Delete
[465] Fix | Delete
# General case, slowest method
[466] Fix | Delete
in1, in2 = tee(iterable)
[467] Fix | Delete
it = izip(imap(key, in1), count(0,-1), in2) # decorate
[468] Fix | Delete
result = _nlargest(n, it)
[469] Fix | Delete
return map(itemgetter(2), result) # undecorate
[470] Fix | Delete
[471] Fix | Delete
if __name__ == "__main__":
[472] Fix | Delete
# Simple sanity test
[473] Fix | Delete
heap = []
[474] Fix | Delete
data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
[475] Fix | Delete
for item in data:
[476] Fix | Delete
heappush(heap, item)
[477] Fix | Delete
sort = []
[478] Fix | Delete
while heap:
[479] Fix | Delete
sort.append(heappop(heap))
[480] Fix | Delete
print sort
[481] Fix | Delete
[482] Fix | Delete
import doctest
[483] Fix | Delete
doctest.testmod()
[484] Fix | Delete
[485] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function