]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.12] Improve all_equal() recipe (gh-116081) (gh-116083)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Wed, 28 Feb 2024 23:11:46 +0000 (00:11 +0100)
committerGitHub <noreply@github.com>
Wed, 28 Feb 2024 23:11:46 +0000 (17:11 -0600)
Doc/library/itertools.rst

index 8ae7a304ff12f42314a78a7ba4490291c3a1c460..82d24a752a4aaae7e34277624e9b5c2f77220dc0 100644 (file)
@@ -855,10 +855,9 @@ which incur interpreter overhead.
        "Given a predicate that returns True or False, count the True results."
        return sum(map(pred, iterable))
 
-   def all_equal(iterable):
+   def all_equal(iterable, key=None):
        "Returns True if all the elements are equal to each other."
-       g = groupby(iterable)
-       return next(g, True) and not next(g, False)
+       return len(take(2, groupby(iterable, key))) <= 1
 
    def first_true(iterable, default=False, pred=None):
        """Returns the first true value in the iterable.
@@ -1217,6 +1216,8 @@ The following recipes have a more mathematical flavor:
 
     >>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')]
     [True, True, True, False, False]
+    >>> [all_equal(s, key=str.casefold) for s in ('', 'A', 'AaAa', 'AAAB', 'AAABA')]
+    [True, True, True, False, False]
 
     >>> quantify(range(99), lambda x: x%2==0)
     50