]> granicus.if.org Git - python/commitdiff
Document another recipe for itertools: all_equal(). Inspired by David Beazley.
authorRaymond Hettinger <python@rcn.com>
Mon, 7 Mar 2016 02:11:38 +0000 (18:11 -0800)
committerRaymond Hettinger <python@rcn.com>
Mon, 7 Mar 2016 02:11:38 +0000 (18:11 -0800)
Doc/library/itertools.rst
Lib/test/test_itertools.py

index 9dac5e19213698033bc24c0c45f12fa3e6e063e0..a9d10736d1cc9502cfd0d3e92d7a5adf45286522 100644 (file)
@@ -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))
index 08c9f3951f3ee500d446d6d65b25d143fb3f3658..f940852ce1b2b8e839147a234e85b742a4731737 100644 (file)
@@ -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