]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.11] gh-102088 Optimize iter_index itertools recipe (GH-102360) (GH-102363)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Thu, 2 Mar 2023 03:52:37 +0000 (19:52 -0800)
committerGitHub <noreply@github.com>
Thu, 2 Mar 2023 03:52:37 +0000 (21:52 -0600)
Doc/library/itertools.rst
Lib/test/test_operator.py

index 2fd30db0587f9690486b389e630c3abeb5bb2737..5fe93fd3e0e5f094e20b536a51fb03eaebc978e2 100644 (file)
@@ -875,9 +875,12 @@ which incur interpreter overhead.
        except AttributeError:
            # Slow path for general iterables
            it = islice(iterable, start, None)
-           for i, element in enumerate(it, start):
-               if element is value or element == value:
-                   yield i
+           i = start - 1
+           try:
+               while True:
+                   yield (i := i + operator.indexOf(it, value) + 1)
+           except ValueError:
+               pass
        else:
            # Fast path for sequences
            i = start - 1
index b7e38c2334987828dea4f017828d678f2d9163c0..1db738d228b1b9e35599954fd0031174d13dd5f0 100644 (file)
@@ -208,6 +208,9 @@ class OperatorTestCase:
         nan = float("nan")
         self.assertEqual(operator.indexOf([nan, nan, 21], nan), 0)
         self.assertEqual(operator.indexOf([{}, 1, {}, 2], {}), 0)
+        it = iter('leave the iterator at exactly the position after the match')
+        self.assertEqual(operator.indexOf(it, 'a'), 2)
+        self.assertEqual(next(it), 'v')
 
     def test_invert(self):
         operator = self.module