From e525ee3b483889313b62b09b4c9103d18dd9cbb7 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Sun, 6 Mar 2016 18:11:38 -0800 Subject: [PATCH] Document another recipe for itertools: all_equal(). Inspired by David Beazley. --- Doc/library/itertools.rst | 5 +++++ Lib/test/test_itertools.py | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index 9dac5e1921..a9d10736d1 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -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)) diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py index 08c9f3951f..f940852ce1 100644 --- a/Lib/test/test_itertools.py +++ b/Lib/test/test_itertools.py @@ -2014,6 +2014,11 @@ Samuele ... "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)) @@ -2127,6 +2132,9 @@ perform as purported. >>> 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 -- 2.40.0