[New-bugs-announce] [issue34210] Small improvements in heapq (refatoring)

Alexander Marshalov report at bugs.python.org
Tue Jul 24 11:06:20 EDT 2018


New submission from Alexander Marshalov <_ at marshalov.org>:

I would like to make three small improvements to the "heapq" module.

1) The "nsmallest" function has the following code (a similar code exists in the "nlargest" function):

    # 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]

   I think "[:n]" is redundant, because "iterable" contains no more than n elements.
   Therefore, that code can be rewritten as follows:
   
    # 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)

2) It seems to me that the line:

    for i in reversed(range(n//2)):

   will be more optimal in this version:

    for i in range(n//2 + 1, -1, -1):


3) Top-level functions can be surrounded with two blank lines for greater compliance with PEP-8.

----------
messages: 322307
nosy: amper
priority: normal
severity: normal
status: open
title: Small improvements in heapq (refatoring)
type: enhancement
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue34210>
_______________________________________


More information about the New-bugs-announce mailing list