mirror of
https://github.com/python/cpython.git
synced 2025-09-27 10:50:04 +00:00
[3.12] Minor clarity improvement for the iter_index() recipe. Also add value subsequence tests. (gh-116696) (gh-116698)
This commit is contained in:
parent
84c8925e13
commit
9f38686f62
1 changed files with 21 additions and 4 deletions
|
@ -894,18 +894,19 @@ which incur interpreter overhead.
|
||||||
# iter_index('AABCADEAF', 'A') --> 0 1 4 7
|
# iter_index('AABCADEAF', 'A') --> 0 1 4 7
|
||||||
seq_index = getattr(iterable, 'index', None)
|
seq_index = getattr(iterable, 'index', None)
|
||||||
if seq_index is None:
|
if seq_index is None:
|
||||||
# Slow path for general iterables
|
# Path for general iterables
|
||||||
it = islice(iterable, start, stop)
|
it = islice(iterable, start, stop)
|
||||||
for i, element in enumerate(it, start):
|
for i, element in enumerate(it, start):
|
||||||
if element is value or element == value:
|
if element is value or element == value:
|
||||||
yield i
|
yield i
|
||||||
else:
|
else:
|
||||||
# Fast path for sequences
|
# Path for sequences with an index() method
|
||||||
stop = len(iterable) if stop is None else stop
|
stop = len(iterable) if stop is None else stop
|
||||||
i = start - 1
|
i = start
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
yield (i := seq_index(value, i+1, stop))
|
yield (i := seq_index(value, i, stop))
|
||||||
|
i += 1
|
||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -1400,6 +1401,22 @@ The following recipes have a more mathematical flavor:
|
||||||
>>> ''.join(input_iterator)
|
>>> ''.join(input_iterator)
|
||||||
'DEAF'
|
'DEAF'
|
||||||
|
|
||||||
|
>>> # Verify that the target value can be a sequence.
|
||||||
|
>>> seq = [[10, 20], [30, 40], 30, 40, [30, 40], 50]
|
||||||
|
>>> target = [30, 40]
|
||||||
|
>>> list(iter_index(seq, target))
|
||||||
|
[1, 4]
|
||||||
|
|
||||||
|
>>> # Verify faithfulness to type specific index() method behaviors.
|
||||||
|
>>> # For example, bytes and str perform subsequence searches
|
||||||
|
>>> # that do not match the general behavior specified
|
||||||
|
>>> # in collections.abc.Sequence.index().
|
||||||
|
>>> seq = 'abracadabra'
|
||||||
|
>>> target = 'ab'
|
||||||
|
>>> list(iter_index(seq, target))
|
||||||
|
[0, 7]
|
||||||
|
|
||||||
|
|
||||||
>>> list(sieve(30))
|
>>> list(sieve(30))
|
||||||
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
|
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
|
||||||
>>> small_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
|
>>> small_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue