Skip to content

Commit

Permalink
Document another recipe for itertools: all_equal(). Inspired by David…
Browse files Browse the repository at this point in the history
… Beazley.
  • Loading branch information
rhettinger committed Mar 7, 2016
1 parent d66dd5c commit e525ee3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
5 changes: 5 additions & 0 deletions Doc/library/itertools.rst
Original file line number Diff line number Diff line change
Expand Up @@ -693,6 +693,11 @@ which incur interpreter overhead.
"Returns the nth item or a default value"
return next(islice(iterable, n, None), default)

def all_equal(iterable):
"Returns True if all the elements are equal to each other"
g = groupby(iterable)
return next(g, True) and not next(g, False)

def quantify(iterable, pred=bool):
"Count how many times the predicate is true"
return sum(map(pred, iterable))
Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_itertools.py
Original file line number Diff line number Diff line change
Expand Up @@ -2014,6 +2014,11 @@ def test_permutations_sizeof(self):
... "Returns the nth item or a default value"
... return next(islice(iterable, n, None), default)
>>> def all_equal(iterable):
... "Returns True if all the elements are equal to each other"
... g = groupby(iterable)
... return next(g, True) and not next(g, False)
>>> def quantify(iterable, pred=bool):
... "Count how many times the predicate is true"
... return sum(map(pred, iterable))
Expand Down Expand Up @@ -2127,6 +2132,9 @@ def test_permutations_sizeof(self):
>>> nth('abcde', 9) is None
True
>>> [all_equal(s) 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 e525ee3

Please sign in to comment.