[Python-checkins] cpython (2.7): Document another recipe for itertools: all_equal(). Inspired by David Beazley.
raymond.hettinger
python-checkins at python.org
Sun Mar 6 21:06:39 EST 2016
https://hg.python.org/cpython/rev/82add23abc54
changeset: 100436:82add23abc54
branch: 2.7
parent: 100432:d135799e952b
user: Raymond Hettinger <python at rcn.com>
date: Sun Mar 06 18:06:29 2016 -0800
summary:
Document another recipe for itertools: all_equal(). Inspired by David Beazley.
files:
Doc/library/itertools.rst | 5 +++++
Lib/test/test_itertools.py | 8 ++++++++
2 files changed, 13 insertions(+), 0 deletions(-)
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -695,6 +695,11 @@
"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(imap(pred, iterable))
diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -1525,6 +1525,11 @@
... "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(imap(pred, iterable))
@@ -1623,6 +1628,9 @@
>>> nth('abcde', 9) is None
True
+>>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')]
+[True, True, True, False, False]
+
>>> quantify(xrange(99), lambda x: x%2==0)
50
--
Repository URL: https://hg.python.org/cpython
More information about the Python-checkins
mailing list