Skip to content

is_sorted: don't double-negate #876

@pochmann3

Description

@pochmann3

The comparisons are all the opposite of what you'd expect from the flags. It's confusing/irritating:

def is_sorted(iterable, key=None, reverse=False, strict=False):
    compare = (le if reverse else ge) if strict else (lt if reverse else gt)

And results are fed to not any:

    it = iterable if key is None else map(key, iterable)
    return not any(starmap(compare, pairwise(it)))

Better use the straightforward comparison and simply all. Or if there's a good reason for the current way (I couldn't find one), there should be a comment explaining it.

Proposal:

def is_sorted(iterable, key=None, reverse=False, strict=False):
    compare = (gt if reverse else lt) if strict else (ge if reverse else le)
    it = iterable if key is None else map(key, iterable)
    return all(starmap(compare, pairwise(it)))

I suspect the current way is like it is because it previously did the following, to avoid a not operation for every element (although I think at least CPython would optimize that away anyway):

    for a, b in pairwise(it):
        if compare(a, b):
            return False

    return True

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions