]> 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:06:29 +0000 (18:06 -0800)
committerRaymond Hettinger <python@rcn.com>
Mon, 7 Mar 2016 02:06:29 +0000 (18:06 -0800)
Doc/library/itertools.rst
Lib/test/test_itertools.py

index ea279b01252928109e5863011825e2fa1c4adabf..a48f69274ae16beddee9ec09b2520279f4574e5e 100644 (file)
@@ -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))
index 753aa17afa428e6e952c27274ce9bceaf46ed02a..8b5f051f18ee099a2e6e4187973913bb02783a8a 100644 (file)
@@ -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