-
Notifications
You must be signed in to change notification settings - Fork 311
is_sorted: don't double-negate #876
Copy link
Copy link
Closed
Description
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 TrueReactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels