SILENT KILLERPanel

Current Path: > > opt > > alt > python39 > lib64 > python3.9 >


Operation   : Linux premium131.web-hosting.com 4.18.0-553.44.1.lve.el8.x86_64 #1 SMP Thu Mar 13 14:29:12 UTC 2025 x86_64
Software     : Apache
Server IP    : 162.0.232.56 | Your IP: 216.73.216.111
Domains      : 1034 Domain(s)
Permission   : [ 0755 ]

Files and Folders in: //opt//alt/python39/lib64/python3.9/

NameTypeSizeLast ModifiedActions
__pycache__ Directory - -
asyncio Directory - -
collections Directory - -
concurrent Directory - -
config-3.9-x86_64-linux-gnu Directory - -
ctypes Directory - -
curses Directory - -
dbm Directory - -
distutils Directory - -
email Directory - -
encodings Directory - -
ensurepip Directory - -
html Directory - -
http Directory - -
importlib Directory - -
json Directory - -
lib-dynload Directory - -
lib2to3 Directory - -
logging Directory - -
multiprocessing Directory - -
pydoc_data Directory - -
site-packages Directory - -
sqlite3 Directory - -
unittest Directory - -
urllib Directory - -
venv Directory - -
wsgiref Directory - -
xml Directory - -
xmlrpc Directory - -
zoneinfo Directory - -
LICENSE.txt File 13937 bytes June 03 2025 18:47:52.
__future__.py File 5147 bytes June 03 2025 18:47:52.
__phello__.foo.py File 64 bytes June 03 2025 18:47:52.
_aix_support.py File 3389 bytes June 03 2025 18:47:52.
_bootlocale.py File 1801 bytes June 03 2025 18:47:52.
_bootsubprocess.py File 2675 bytes June 03 2025 18:47:52.
_collections_abc.py File 29374 bytes June 03 2025 18:47:52.
_compat_pickle.py File 8749 bytes June 03 2025 18:47:52.
_compression.py File 5340 bytes June 03 2025 18:47:52.
_markupbase.py File 14623 bytes June 03 2025 18:47:52.
_osx_support.py File 21773 bytes June 03 2025 18:47:52.
_py_abc.py File 6189 bytes June 03 2025 18:47:52.
_pydecimal.py File 228666 bytes June 03 2025 18:47:52.
_pyio.py File 93316 bytes June 03 2025 18:47:52.
_sitebuiltins.py File 3115 bytes June 03 2025 18:47:52.
_strptime.py File 25277 bytes June 03 2025 18:47:52.
_sysconfigdata__linux_x86_64-linux-gnu.py File 40536 bytes June 19 2025 12:09:48.
_sysconfigdata_d_linux_x86_64-linux-gnu.py File 40272 bytes June 19 2025 12:00:02.
_threading_local.py File 7220 bytes June 03 2025 18:47:52.
_weakrefset.py File 5923 bytes June 03 2025 18:47:52.
abc.py File 4920 bytes June 03 2025 18:47:52.
aifc.py File 32605 bytes June 03 2025 18:47:52.
antigravity.py File 500 bytes June 03 2025 18:47:52.
argparse.py File 98119 bytes June 03 2025 18:47:52.
ast.py File 56256 bytes June 03 2025 18:47:52.
asynchat.py File 11321 bytes June 03 2025 18:47:52.
asyncore.py File 20102 bytes June 03 2025 18:47:52.
base64.py File 19872 bytes June 03 2025 18:47:52.
bdb.py File 31389 bytes June 03 2025 18:47:52.
binhex.py File 14784 bytes June 03 2025 18:47:52.
bisect.py File 2350 bytes June 03 2025 18:47:52.
bz2.py File 12447 bytes June 03 2025 18:47:52.
cProfile.py File 6358 bytes June 03 2025 18:47:52.
calendar.py File 24832 bytes June 03 2025 18:47:52.
cgi.py File 33945 bytes June 03 2025 18:47:52.
cgitb.py File 12096 bytes June 03 2025 18:47:52.
chunk.py File 5435 bytes June 03 2025 18:47:52.
cmd.py File 14860 bytes June 03 2025 18:47:52.
code.py File 10622 bytes June 03 2025 18:47:52.
codecs.py File 36673 bytes June 03 2025 18:47:52.
codeop.py File 6326 bytes June 03 2025 18:47:52.
colorsys.py File 4064 bytes June 03 2025 18:47:52.
compileall.py File 20105 bytes June 03 2025 18:47:52.
configparser.py File 54584 bytes June 03 2025 18:47:52.
contextlib.py File 24624 bytes June 03 2025 18:47:52.
contextvars.py File 129 bytes June 03 2025 18:47:52.
copy.py File 8650 bytes June 03 2025 18:47:52.
copyreg.py File 7274 bytes June 03 2025 18:47:52.
crypt.py File 3819 bytes June 03 2025 18:47:52.
csv.py File 16144 bytes June 03 2025 18:47:52.
dataclasses.py File 49586 bytes June 03 2025 18:47:52.
datetime.py File 89177 bytes June 03 2025 18:47:52.
decimal.py File 320 bytes June 03 2025 18:47:52.
difflib.py File 83307 bytes June 03 2025 18:47:52.
dis.py File 20570 bytes June 03 2025 18:47:52.
doctest.py File 104568 bytes June 03 2025 18:47:52.
enum.py File 39440 bytes June 03 2025 18:47:52.
filecmp.py File 10024 bytes June 03 2025 18:47:52.
fileinput.py File 14791 bytes June 03 2025 18:47:52.
fnmatch.py File 6004 bytes June 03 2025 18:47:52.
formatter.py File 15143 bytes June 03 2025 18:47:52.
fractions.py File 24323 bytes June 03 2025 18:47:52.
ftplib.py File 35496 bytes June 03 2025 18:47:52.
functools.py File 38881 bytes June 03 2025 18:47:52.
genericpath.py File 5246 bytes June 03 2025 18:47:52.
getopt.py File 7489 bytes June 03 2025 18:47:52.
getpass.py File 5990 bytes June 03 2025 18:47:52.
gettext.py File 27266 bytes June 03 2025 18:47:52.
glob.py File 5823 bytes June 03 2025 18:47:52.
graphlib.py File 9573 bytes June 03 2025 18:47:52.
gzip.py File 21772 bytes June 03 2025 18:47:52.
hashlib.py File 10010 bytes June 03 2025 18:47:52.
heapq.py File 22877 bytes June 03 2025 18:47:52.
hmac.py File 7003 bytes June 03 2025 18:47:52.
imaplib.py File 55256 bytes June 03 2025 18:47:52.
imghdr.py File 3808 bytes June 03 2025 18:47:52.
imp.py File 10536 bytes June 03 2025 18:47:52.
inspect.py File 118235 bytes June 03 2025 18:47:52.
io.py File 3541 bytes June 03 2025 18:47:52.
ipaddress.py File 80924 bytes June 03 2025 18:47:52.
keyword.py File 1047 bytes June 03 2025 18:47:52.
linecache.py File 5461 bytes June 03 2025 18:47:52.
locale.py File 78271 bytes June 03 2025 18:47:52.
lzma.py File 13231 bytes June 03 2025 18:47:52.
mailbox.py File 78794 bytes June 03 2025 18:47:52.
mailcap.py File 9116 bytes June 03 2025 18:47:52.
mimetypes.py File 21564 bytes June 03 2025 18:47:52.
modulefinder.py File 24401 bytes June 03 2025 18:47:52.
netrc.py File 5566 bytes June 03 2025 18:47:52.
nntplib.py File 41023 bytes June 03 2025 18:47:52.
ntpath.py File 28259 bytes June 03 2025 18:47:52.
nturl2path.py File 2887 bytes June 03 2025 18:47:52.
numbers.py File 10338 bytes June 03 2025 18:47:52.
opcode.py File 5660 bytes June 03 2025 18:47:52.
operator.py File 10751 bytes June 03 2025 18:47:52.
optparse.py File 60369 bytes June 03 2025 18:47:52.
os.py File 39065 bytes June 03 2025 18:47:52.
pathlib.py File 51134 bytes June 03 2025 18:47:52.
pdb.py File 63250 bytes June 03 2025 18:47:52.
pickle.py File 64920 bytes June 03 2025 18:47:52.
pickletools.py File 93486 bytes June 03 2025 18:47:52.
pipes.py File 8916 bytes June 03 2025 18:47:52.
pkgutil.py File 24276 bytes June 03 2025 18:47:52.
platform.py File 40614 bytes June 03 2025 18:47:52.
plistlib.py File 28248 bytes June 03 2025 18:47:52.
poplib.py File 15198 bytes June 03 2025 18:47:52.
posixpath.py File 16273 bytes June 03 2025 18:47:52.
pprint.py File 22527 bytes June 03 2025 18:47:52.
profile.py File 22894 bytes June 03 2025 18:47:52.
pstats.py File 29326 bytes June 03 2025 18:47:52.
pty.py File 4807 bytes June 03 2025 18:47:52.
py_compile.py File 8203 bytes June 19 2025 11:56:56.
pyclbr.py File 15255 bytes June 03 2025 18:47:52.
pydoc.py File 109612 bytes June 03 2025 18:47:52.
queue.py File 11496 bytes June 03 2025 18:47:52.
quopri.py File 7279 bytes June 03 2025 18:47:52.
random.py File 31484 bytes June 03 2025 18:47:52.
re.py File 15861 bytes June 03 2025 18:47:52.
reprlib.py File 5267 bytes June 03 2025 18:47:52.
rlcompleter.py File 7648 bytes June 03 2025 18:47:52.
runpy.py File 13084 bytes June 03 2025 18:47:52.
sched.py File 6442 bytes June 03 2025 18:47:52.
secrets.py File 2036 bytes June 03 2025 18:47:52.
selectors.py File 19536 bytes June 03 2025 18:47:52.
shelve.py File 8527 bytes June 03 2025 18:47:52.
shlex.py File 13501 bytes June 03 2025 18:47:52.
shutil.py File 53030 bytes June 03 2025 18:47:52.
signal.py File 2438 bytes June 03 2025 18:47:52.
site.py File 21844 bytes June 03 2025 18:47:52.
smtpd.py File 34834 bytes June 03 2025 18:47:52.
smtplib.py File 45418 bytes June 03 2025 18:47:52.
sndhdr.py File 7099 bytes June 03 2025 18:47:52.
socket.py File 36915 bytes June 03 2025 18:47:52.
socketserver.py File 27296 bytes June 03 2025 18:47:52.
sre_compile.py File 27973 bytes June 03 2025 18:47:52.
sre_constants.py File 7177 bytes June 03 2025 18:47:52.
sre_parse.py File 40779 bytes June 03 2025 18:47:52.
ssl.py File 52530 bytes June 03 2025 18:47:52.
stat.py File 5485 bytes June 03 2025 18:47:52.
statistics.py File 38067 bytes June 03 2025 18:47:52.
string.py File 10566 bytes June 03 2025 18:47:52.
stringprep.py File 12917 bytes June 03 2025 18:47:52.
struct.py File 257 bytes June 03 2025 18:47:52.
subprocess.py File 83564 bytes June 03 2025 18:47:52.
sunau.py File 18158 bytes June 03 2025 18:47:52.
symbol.py File 2281 bytes June 19 2025 12:01:19.
symtable.py File 7905 bytes June 03 2025 18:47:52.
sysconfig.py File 24914 bytes June 03 2025 18:47:52.
tabnanny.py File 11419 bytes June 03 2025 18:47:52.
tarfile.py File 110849 bytes June 03 2025 18:47:52.
telnetlib.py File 23254 bytes June 03 2025 18:47:52.
tempfile.py File 27963 bytes June 03 2025 18:47:52.
textwrap.py File 19407 bytes June 03 2025 18:47:52.
this.py File 1003 bytes June 03 2025 18:47:52.
threading.py File 54176 bytes June 03 2025 18:47:52.
timeit.py File 13493 bytes June 03 2025 18:47:52.
token.py File 2368 bytes June 03 2025 18:47:52.
tokenize.py File 25883 bytes June 03 2025 18:47:52.
trace.py File 29220 bytes June 03 2025 18:47:52.
traceback.py File 24660 bytes June 03 2025 18:47:52.
tracemalloc.py File 18047 bytes June 03 2025 18:47:52.
tty.py File 879 bytes June 03 2025 18:47:52.
types.py File 9785 bytes June 03 2025 18:47:52.
typing.py File 77044 bytes June 03 2025 18:47:52.
uu.py File 7277 bytes June 19 2025 12:10:58.
uuid.py File 27324 bytes June 03 2025 18:47:52.
warnings.py File 19688 bytes June 03 2025 18:47:52.
wave.py File 18004 bytes June 03 2025 18:47:52.
weakref.py File 21560 bytes June 03 2025 18:47:52.
webbrowser.py File 24096 bytes June 03 2025 18:47:52.
xdrlib.py File 5913 bytes June 03 2025 18:47:52.
zipapp.py File 7535 bytes June 03 2025 18:47:52.
zipfile.py File 88240 bytes June 03 2025 18:47:52.
zipimport.py File 30765 bytes June 03 2025 18:47:52.

Reading File: //opt//alt/python39/lib64/python3.9//heapq.py

"""Heap queue algorithm (a.k.a. priority queue).

Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
all k, counting elements from 0.  For the sake of comparison,
non-existing elements are considered to be infinite.  The interesting
property of a heap is that a[0] is always its smallest element.

Usage:

heap = []            # creates an empty heap
heappush(heap, item) # pushes a new item on the heap
item = heappop(heap) # pops the smallest item from the heap
item = heap[0]       # smallest item on the heap without popping it
heapify(x)           # transforms list into a heap, in-place, in linear time
item = heapreplace(heap, item) # pops and returns smallest item, and adds
                               # new item; the heap size is unchanged

Our API differs from textbook heap algorithms as follows:

- We use 0-based indexing.  This makes the relationship between the
  index for a node and the indexes for its children slightly less
  obvious, but is more suitable since Python uses 0-based indexing.

- Our heappop() method returns the smallest item, not the largest.

These two make it possible to view the heap as a regular Python list
without surprises: heap[0] is the smallest item, and heap.sort()
maintains the heap invariant!
"""

# Original code by Kevin O'Connor, augmented by Tim Peters and Raymond Hettinger

__about__ = """Heap queues

[explanation by François Pinard]

Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
all k, counting elements from 0.  For the sake of comparison,
non-existing elements are considered to be infinite.  The interesting
property of a heap is that a[0] is always its smallest element.

The strange invariant above is meant to be an efficient memory
representation for a tournament.  The numbers below are `k', not a[k]:

                                   0

                  1                                 2

          3               4                5               6

      7       8       9       10      11      12      13      14

    15 16   17 18   19 20   21 22   23 24   25 26   27 28   29 30


In the tree above, each cell `k' is topping `2*k+1' and `2*k+2'.  In
a usual binary tournament we see in sports, each cell is the winner
over the two cells it tops, and we can trace the winner down the tree
to see all opponents s/he had.  However, in many computer applications
of such tournaments, we do not need to trace the history of a winner.
To be more memory efficient, when a winner is promoted, we try to
replace it by something else at a lower level, and the rule becomes
that a cell and the two cells it tops contain three different items,
but the top cell "wins" over the two topped cells.

If this heap invariant is protected at all time, index 0 is clearly
the overall winner.  The simplest algorithmic way to remove it and
find the "next" winner is to move some loser (let's say cell 30 in the
diagram above) into the 0 position, and then percolate this new 0 down
the tree, exchanging values, until the invariant is re-established.
This is clearly logarithmic on the total number of items in the tree.
By iterating over all items, you get an O(n ln n) sort.

A nice feature of this sort is that you can efficiently insert new
items while the sort is going on, provided that the inserted items are
not "better" than the last 0'th element you extracted.  This is
especially useful in simulation contexts, where the tree holds all
incoming events, and the "win" condition means the smallest scheduled
time.  When an event schedule other events for execution, they are
scheduled into the future, so they can easily go into the heap.  So, a
heap is a good structure for implementing schedulers (this is what I
used for my MIDI sequencer :-).

Various structures for implementing schedulers have been extensively
studied, and heaps are good for this, as they are reasonably speedy,
the speed is almost constant, and the worst case is not much different
than the average case.  However, there are other representations which
are more efficient overall, yet the worst cases might be terrible.

Heaps are also very useful in big disk sorts.  You most probably all
know that a big sort implies producing "runs" (which are pre-sorted
sequences, which size is usually related to the amount of CPU memory),
followed by a merging passes for these runs, which merging is often
very cleverly organised[1].  It is very important that the initial
sort produces the longest runs possible.  Tournaments are a good way
to that.  If, using all the memory available to hold a tournament, you
replace and percolate items that happen to fit the current run, you'll
produce runs which are twice the size of the memory for random input,
and much better for input fuzzily ordered.

Moreover, if you output the 0'th item on disk and get an input which
may not fit in the current tournament (because the value "wins" over
the last output value), it cannot fit in the heap, so the size of the
heap decreases.  The freed memory could be cleverly reused immediately
for progressively building a second heap, which grows at exactly the
same rate the first heap is melting.  When the first heap completely
vanishes, you switch heaps and start a new run.  Clever and quite
effective!

In a word, heaps are useful memory structures to know.  I use them in
a few applications, and I think it is good to keep a `heap' module
around. :-)

--------------------
[1] The disk balancing algorithms which are current, nowadays, are
more annoying than clever, and this is a consequence of the seeking
capabilities of the disks.  On devices which cannot seek, like big
tape drives, the story was quite different, and one had to be very
clever to ensure (far in advance) that each tape movement will be the
most effective possible (that is, will best participate at
"progressing" the merge).  Some tapes were even able to read
backwards, and this was also used to avoid the rewinding time.
Believe me, real good tape sorts were quite spectacular to watch!
From all times, sorting has always been a Great Art! :-)
"""

__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge',
           'nlargest', 'nsmallest', 'heappushpop']

def heappush(heap, item):
    """Push item onto heap, maintaining the heap invariant."""
    heap.append(item)
    _siftdown(heap, 0, len(heap)-1)

def heappop(heap):
    """Pop the smallest item off the heap, maintaining the heap invariant."""
    lastelt = heap.pop()    # raises appropriate IndexError if heap is empty
    if heap:
        returnitem = heap[0]
        heap[0] = lastelt
        _siftup(heap, 0)
        return returnitem
    return lastelt

def heapreplace(heap, item):
    """Pop and return the current smallest value, and add the new item.

    This is more efficient than heappop() followed by heappush(), and can be
    more appropriate when using a fixed-size heap.  Note that the value
    returned may be larger than item!  That constrains reasonable uses of
    this routine unless written as part of a conditional replacement:

        if item > heap[0]:
            item = heapreplace(heap, item)
    """
    returnitem = heap[0]    # raises appropriate IndexError if heap is empty
    heap[0] = item
    _siftup(heap, 0)
    return returnitem

def heappushpop(heap, item):
    """Fast version of a heappush followed by a heappop."""
    if heap and heap[0] < item:
        item, heap[0] = heap[0], item
        _siftup(heap, 0)
    return item

def heapify(x):
    """Transform list into a heap, in-place, in O(len(x)) time."""
    n = len(x)
    # Transform bottom-up.  The largest index there's any point to looking at
    # is the largest with a child index in-range, so must have 2*i + 1 < n,
    # or i < (n-1)/2.  If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so
    # j-1 is the largest, which is n//2 - 1.  If n is odd = 2*j+1, this is
    # (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1.
    for i in reversed(range(n//2)):
        _siftup(x, i)

def _heappop_max(heap):
    """Maxheap version of a heappop."""
    lastelt = heap.pop()    # raises appropriate IndexError if heap is empty
    if heap:
        returnitem = heap[0]
        heap[0] = lastelt
        _siftup_max(heap, 0)
        return returnitem
    return lastelt

def _heapreplace_max(heap, item):
    """Maxheap version of a heappop followed by a heappush."""
    returnitem = heap[0]    # raises appropriate IndexError if heap is empty
    heap[0] = item
    _siftup_max(heap, 0)
    return returnitem

def _heapify_max(x):
    """Transform list into a maxheap, in-place, in O(len(x)) time."""
    n = len(x)
    for i in reversed(range(n//2)):
        _siftup_max(x, i)

# 'heap' is a heap at all indices >= startpos, except possibly for pos.  pos
# is the index of a leaf with a possibly out-of-order value.  Restore the
# heap invariant.
def _siftdown(heap, startpos, pos):
    newitem = heap[pos]
    # Follow the path to the root, moving parents down until finding a place
    # newitem fits.
    while pos > startpos:
        parentpos = (pos - 1) >> 1
        parent = heap[parentpos]
        if newitem < parent:
            heap[pos] = parent
            pos = parentpos
            continue
        break
    heap[pos] = newitem

# The child indices of heap index pos are already heaps, and we want to make
# a heap at index pos too.  We do this by bubbling the smaller child of
# pos up (and so on with that child's children, etc) until hitting a leaf,
# then using _siftdown to move the oddball originally at index pos into place.
#
# We *could* break out of the loop as soon as we find a pos where newitem <=
# both its children, but turns out that's not a good idea, and despite that
# many books write the algorithm that way.  During a heap pop, the last array
# element is sifted in, and that tends to be large, so that comparing it
# against values starting from the root usually doesn't pay (= usually doesn't
# get us out of the loop early).  See Knuth, Volume 3, where this is
# explained and quantified in an exercise.
#
# Cutting the # of comparisons is important, since these routines have no
# way to extract "the priority" from an array element, so that intelligence
# is likely to be hiding in custom comparison methods, or in array elements
# storing (priority, record) tuples.  Comparisons are thus potentially
# expensive.
#
# On random arrays of length 1000, making this change cut the number of
# comparisons made by heapify() a little, and those made by exhaustive
# heappop() a lot, in accord with theory.  Here are typical results from 3
# runs (3 just to demonstrate how small the variance is):
#
# Compares needed by heapify     Compares needed by 1000 heappops
# --------------------------     --------------------------------
# 1837 cut to 1663               14996 cut to 8680
# 1855 cut to 1659               14966 cut to 8678
# 1847 cut to 1660               15024 cut to 8703
#
# Building the heap by using heappush() 1000 times instead required
# 2198, 2148, and 2219 compares:  heapify() is more efficient, when
# you can use it.
#
# The total compares needed by list.sort() on the same lists were 8627,
# 8627, and 8632 (this should be compared to the sum of heapify() and
# heappop() compares):  list.sort() is (unsurprisingly!) more efficient
# for sorting.

def _siftup(heap, pos):
    endpos = len(heap)
    startpos = pos
    newitem = heap[pos]
    # Bubble up the smaller child until hitting a leaf.
    childpos = 2*pos + 1    # leftmost child position
    while childpos < endpos:
        # Set childpos to index of smaller child.
        rightpos = childpos + 1
        if rightpos < endpos and not heap[childpos] < heap[rightpos]:
            childpos = rightpos
        # Move the smaller child up.
        heap[pos] = heap[childpos]
        pos = childpos
        childpos = 2*pos + 1
    # The leaf at pos is empty now.  Put newitem there, and bubble it up
    # to its final resting place (by sifting its parents down).
    heap[pos] = newitem
    _siftdown(heap, startpos, pos)

def _siftdown_max(heap, startpos, pos):
    'Maxheap variant of _siftdown'
    newitem = heap[pos]
    # Follow the path to the root, moving parents down until finding a place
    # newitem fits.
    while pos > startpos:
        parentpos = (pos - 1) >> 1
        parent = heap[parentpos]
        if parent < newitem:
            heap[pos] = parent
            pos = parentpos
            continue
        break
    heap[pos] = newitem

def _siftup_max(heap, pos):
    'Maxheap variant of _siftup'
    endpos = len(heap)
    startpos = pos
    newitem = heap[pos]
    # Bubble up the larger child until hitting a leaf.
    childpos = 2*pos + 1    # leftmost child position
    while childpos < endpos:
        # Set childpos to index of larger child.
        rightpos = childpos + 1
        if rightpos < endpos and not heap[rightpos] < heap[childpos]:
            childpos = rightpos
        # Move the larger child up.
        heap[pos] = heap[childpos]
        pos = childpos
        childpos = 2*pos + 1
    # The leaf at pos is empty now.  Put newitem there, and bubble it up
    # to its final resting place (by sifting its parents down).
    heap[pos] = newitem
    _siftdown_max(heap, startpos, pos)

def merge(*iterables, key=None, reverse=False):
    '''Merge multiple sorted inputs into a single sorted output.

    Similar to sorted(itertools.chain(*iterables)) but returns a generator,
    does not pull the data into memory all at once, and assumes that each of
    the input streams is already sorted (smallest to largest).

    >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))
    [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]

    If *key* is not None, applies a key function to each element to determine
    its sort order.

    >>> list(merge(['dog', 'horse'], ['cat', 'fish', 'kangaroo'], key=len))
    ['dog', 'cat', 'fish', 'horse', 'kangaroo']

    '''

    h = []
    h_append = h.append

    if reverse:
        _heapify = _heapify_max
        _heappop = _heappop_max
        _heapreplace = _heapreplace_max
        direction = -1
    else:
        _heapify = heapify
        _heappop = heappop
        _heapreplace = heapreplace
        direction = 1

    if key is None:
        for order, it in enumerate(map(iter, iterables)):
            try:
                next = it.__next__
                h_append([next(), order * direction, next])
            except StopIteration:
                pass
        _heapify(h)
        while len(h) > 1:
            try:
                while True:
                    value, order, next = s = h[0]
                    yield value
                    s[0] = next()           # raises StopIteration when exhausted
                    _heapreplace(h, s)      # restore heap condition
            except StopIteration:
                _heappop(h)                 # remove empty iterator
        if h:
            # fast case when only a single iterator remains
            value, order, next = h[0]
            yield value
            yield from next.__self__
        return

    for order, it in enumerate(map(iter, iterables)):
        try:
            next = it.__next__
            value = next()
            h_append([key(value), order * direction, value, next])
        except StopIteration:
            pass
    _heapify(h)
    while len(h) > 1:
        try:
            while True:
                key_value, order, value, next = s = h[0]
                yield value
                value = next()
                s[0] = key(value)
                s[2] = value
                _heapreplace(h, s)
        except StopIteration:
            _heappop(h)
    if h:
        key_value, order, value, next = h[0]
        yield value
        yield from next.__self__


# Algorithm notes for nlargest() and nsmallest()
# ==============================================
#
# Make a single pass over the data while keeping the k most extreme values
# in a heap.  Memory consumption is limited to keeping k values in a list.
#
# Measured performance for random inputs:
#
#                                   number of comparisons
#    n inputs     k-extreme values  (average of 5 trials)   % more than min()
# -------------   ----------------  ---------------------   -----------------
#      1,000           100                  3,317               231.7%
#     10,000           100                 14,046                40.5%
#    100,000           100                105,749                 5.7%
#  1,000,000           100              1,007,751                 0.8%
# 10,000,000           100             10,009,401                 0.1%
#
# Theoretical number of comparisons for k smallest of n random inputs:
#
# Step   Comparisons                  Action
# ----   --------------------------   ---------------------------
#  1     1.66 * k                     heapify the first k-inputs
#  2     n - k                        compare remaining elements to top of heap
#  3     k * (1 + lg2(k)) * ln(n/k)   replace the topmost value on the heap
#  4     k * lg2(k) - (k/2)           final sort of the k most extreme values
#
# Combining and simplifying for a rough estimate gives:
#
#        comparisons = n + k * (log(k, 2) * log(n/k) + log(k, 2) + log(n/k))
#
# Computing the number of comparisons for step 3:
# -----------------------------------------------
# * For the i-th new value from the iterable, the probability of being in the
#   k most extreme values is k/i.  For example, the probability of the 101st
#   value seen being in the 100 most extreme values is 100/101.
# * If the value is a new extreme value, the cost of inserting it into the
#   heap is 1 + log(k, 2).
# * The probability times the cost gives:
#            (k/i) * (1 + log(k, 2))
# * Summing across the remaining n-k elements gives:
#            sum((k/i) * (1 + log(k, 2)) for i in range(k+1, n+1))
# * This reduces to:
#            (H(n) - H(k)) * k * (1 + log(k, 2))
# * Where H(n) is the n-th harmonic number estimated by:
#            gamma = 0.5772156649
#            H(n) = log(n, e) + gamma + 1 / (2 * n)
#   http://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#Rate_of_divergence
# * Substituting the H(n) formula:
#            comparisons = k * (1 + log(k, 2)) * (log(n/k, e) + (1/n - 1/k) / 2)
#
# Worst-case for step 3:
# ----------------------
# In the worst case, the input data is reversed sorted so that every new element
# must be inserted in the heap:
#
#             comparisons = 1.66 * k + log(k, 2) * (n - k)
#
# Alternative Algorithms
# ----------------------
# Other algorithms were not used because they:
# 1) Took much more auxiliary memory,
# 2) Made multiple passes over the data.
# 3) Made more comparisons in common cases (small k, large n, semi-random input).
# See the more detailed comparison of approach at:
# http://code.activestate.com/recipes/577573-compare-algorithms-for-heapqsmallest

def nsmallest(n, iterable, key=None):
    """Find the n smallest elements in a dataset.

    Equivalent to:  sorted(iterable, key=key)[:n]
    """

    # Short-cut for n==1 is to use min()
    if n == 1:
        it = iter(iterable)
        sentinel = object()
        result = min(it, default=sentinel, key=key)
        return [] if result is sentinel else [result]

    # When n>=size, it's faster to use sorted()
    try:
        size = len(iterable)
    except (TypeError, AttributeError):
        pass
    else:
        if n >= size:
            return sorted(iterable, key=key)[:n]

    # When key is none, use simpler decoration
    if key is None:
        it = iter(iterable)
        # put the range(n) first so that zip() doesn't
        # consume one too many elements from the iterator
        result = [(elem, i) for i, elem in zip(range(n), it)]
        if not result:
            return result
        _heapify_max(result)
        top = result[0][0]
        order = n
        _heapreplace = _heapreplace_max
        for elem in it:
            if elem < top:
                _heapreplace(result, (elem, order))
                top, _order = result[0]
                order += 1
        result.sort()
        return [elem for (elem, order) in result]

    # General case, slowest method
    it = iter(iterable)
    result = [(key(elem), i, elem) for i, elem in zip(range(n), it)]
    if not result:
        return result
    _heapify_max(result)
    top = result[0][0]
    order = n
    _heapreplace = _heapreplace_max
    for elem in it:
        k = key(elem)
        if k < top:
            _heapreplace(result, (k, order, elem))
            top, _order, _elem = result[0]
            order += 1
    result.sort()
    return [elem for (k, order, elem) in result]

def nlargest(n, iterable, key=None):
    """Find the n largest elements in a dataset.

    Equivalent to:  sorted(iterable, key=key, reverse=True)[:n]
    """

    # Short-cut for n==1 is to use max()
    if n == 1:
        it = iter(iterable)
        sentinel = object()
        result = max(it, default=sentinel, key=key)
        return [] if result is sentinel else [result]

    # When n>=size, it's faster to use sorted()
    try:
        size = len(iterable)
    except (TypeError, AttributeError):
        pass
    else:
        if n >= size:
            return sorted(iterable, key=key, reverse=True)[:n]

    # When key is none, use simpler decoration
    if key is None:
        it = iter(iterable)
        result = [(elem, i) for i, elem in zip(range(0, -n, -1), it)]
        if not result:
            return result
        heapify(result)
        top = result[0][0]
        order = -n
        _heapreplace = heapreplace
        for elem in it:
            if top < elem:
                _heapreplace(result, (elem, order))
                top, _order = result[0]
                order -= 1
        result.sort(reverse=True)
        return [elem for (elem, order) in result]

    # General case, slowest method
    it = iter(iterable)
    result = [(key(elem), i, elem) for i, elem in zip(range(0, -n, -1), it)]
    if not result:
        return result
    heapify(result)
    top = result[0][0]
    order = -n
    _heapreplace = heapreplace
    for elem in it:
        k = key(elem)
        if top < k:
            _heapreplace(result, (k, order, elem))
            top, _order, _elem = result[0]
            order -= 1
    result.sort(reverse=True)
    return [elem for (k, order, elem) in result]

# If available, use C implementation
try:
    from _heapq import *
except ImportError:
    pass
try:
    from _heapq import _heapreplace_max
except ImportError:
    pass
try:
    from _heapq import _heapify_max
except ImportError:
    pass
try:
    from _heapq import _heappop_max
except ImportError:
    pass


if __name__ == "__main__":

    import doctest # pragma: no cover
    print(doctest.testmod()) # pragma: no cover

SILENT KILLER Tool