From 148bde644195408ec68cd145b779f42a214bfbb1 Mon Sep 17 00:00:00 2001 From: Stefan Pochmann <609905+pochmann@users.noreply.github.com> Date: Wed, 1 Mar 2023 23:36:49 +0100 Subject: [PATCH 1/2] Optimize iter_index itertools recipe --- Doc/library/itertools.rst | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index 95da7166842ee6..d85a17effb04a2 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -886,9 +886,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 From 0b0b81c20aa2b327fc00bb6128acbdc3e9d15d3b Mon Sep 17 00:00:00 2001 From: Stefan Pochmann <609905+pochmann@users.noreply.github.com> Date: Thu, 2 Mar 2023 00:02:11 +0100 Subject: [PATCH 2/2] Add test for operator.indexOf on iterators For the new iter_index itertools recipe version relying on this. --- Lib/test/test_operator.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Lib/test/test_operator.py b/Lib/test/test_operator.py index b7e38c23349878..1db738d228b1b9 100644 --- a/Lib/test/test_operator.py +++ b/Lib/test/test_operator.py @@ -208,6 +208,9 @@ def test_indexOf(self): 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