summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2016-03-07 02:06:29 (GMT)
committerRaymond Hettinger <python@rcn.com>2016-03-07 02:06:29 (GMT)
commit2ec5fd546f5fb98f84e3910301d53cfa30add15d (patch)
tree87f6b512772ac3066f86ddeae6f0435ce47e01e2
parent87640b30cef32377be844a16129fcb449ccaec29 (diff)
downloadcpython-2ec5fd546f5fb98f84e3910301d53cfa30add15d.zip
cpython-2ec5fd546f5fb98f84e3910301d53cfa30add15d.tar.gz
cpython-2ec5fd546f5fb98f84e3910301d53cfa30add15d.tar.bz2
Document another recipe for itertools: all_equal(). Inspired by David Beazley.
-rw-r--r--Doc/library/itertools.rst5
-rw-r--r--Lib/test/test_itertools.py8
2 files changed, 13 insertions, 0 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
index ea279b0..a48f692 100644
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -695,6 +695,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(imap(pred, iterable))
diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
index 753aa17..8b5f051 100644
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -1525,6 +1525,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(imap(pred, iterable))
@@ -1623,6 +1628,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(xrange(99), lambda x: x%2==0)
50