Skip to content

Commit

Permalink
Improve all_equal() recipe (pythongh-116081)
Browse files Browse the repository at this point in the history
Replace conjuction of next() calls with simpler len()/take() logic. Add key function.
  • Loading branch information
rhettinger authored and woodruffw committed Mar 4, 2024
1 parent 75756a7 commit e8dfde0
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions Doc/library/itertools.rst
Original file line number Diff line number Diff line change
Expand Up @@ -863,10 +863,9 @@ which incur interpreter overhead.
"Given a predicate that returns True or False, count the True results."
return sum(map(pred, iterable))

def all_equal(iterable):
def all_equal(iterable, key=None):
"Returns True if all the elements are equal to each other."
g = groupby(iterable)
return next(g, True) and not next(g, False)
return len(take(2, groupby(iterable, key))) <= 1

def first_true(iterable, default=False, pred=None):
"""Returns the first true value in the iterable.
Expand Down Expand Up @@ -1225,6 +1224,8 @@ The following recipes have a more mathematical flavor:

>>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')]
[True, True, True, False, False]
>>> [all_equal(s, key=str.casefold) for s in ('', 'A', 'AaAa', 'AAAB', 'AAABA')]
[True, True, True, False, False]

>>> quantify(range(99), lambda x: x%2==0)
50
Expand Down

0 comments on commit e8dfde0

Please sign in to comment.