Iteration Tools · Practice
Quiz & exercises
Answer each question to see the explanation. Your best score is saved in this browser.
Quiz
Coding exercises
Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.
Exercise 1: The first n matches, lazily ✓ Passed
Write first_matches(iterable, predicate, n) that returns a list of the first n items of iterable for which predicate(item) is truthy.
It must work on infinite iterators (so it may not consume more than it needs), and if fewer than n items match, return all the matches. Try to solve it with filter and itertools.islice rather than a manual loop.
from itertools import islice
def first_matches(iterable, predicate, n):
# your code here
pass
from itertools import count
def test_basic():
"""first 3 even numbers from a list"""
assert first_matches([1, 2, 3, 4, 5, 6, 8], lambda x: x % 2 == 0, 3) == [2, 4, 6]
def test_infinite():
"""works on an infinite iterator"""
result = first_matches(count(1), lambda x: x % 7 == 0, 4)
assert result == [7, 14, 21, 28], f"got {result}"
def test_not_enough():
"""fewer matches than n returns all of them"""
assert first_matches('banana', lambda c: c == 'a', 10) == ['a', 'a', 'a']
def test_stops_early():
"""does not consume more of the iterator than needed"""
it = iter(range(100))
first_matches(it, lambda x: x > 2, 2)
assert next(it) == 5, "the iterator was consumed past the second match"
def test_returns_list():
"""returns a list"""
assert isinstance(first_matches(range(5), bool, 2), list)
Hints (2)
filter(predicate, iterable)is lazy: it produces matches one at a time.islice(something, n)stops afternitems, so it never asks the filter for more.
Show a solution
from itertools import islice
def first_matches(iterable, predicate, n):
return list(islice(filter(predicate, iterable), n))Exercise 2: Round-robin interleaving ✓ Passed
Write a generator function interleave(*iterables) that yields one item from each iterable in turn, skipping iterables that have run out, until all are exhausted.
For example, list(interleave('ABC', [1, 2], 'xyzw')) is ['A', 1, 'x', 'B', 2, 'y', 'C', 'z', 'w'].
Values like None or 0 inside the data must be kept. A neat approach combines zip_longest, a unique sentinel fillvalue, and chain.from_iterable.
from itertools import zip_longest, chain
def interleave(*iterables):
for group in zip(*iterables):
yield from group
import types
def test_example():
"""the example from the prompt"""
result = list(interleave('ABC', [1, 2], 'xyzw'))
assert result == ['A', 1, 'x', 'B', 2, 'y', 'C', 'z', 'w'], f"got {result}"
def test_keeps_none_and_zero():
"""None and 0 in the data are kept"""
result = list(interleave([None, 0], [False]))
assert result == [None, False, 0], f"got {result}"
def test_generators():
"""works with generators"""
result = list(interleave((i for i in range(3)), (c for c in 'ab')))
assert result == [0, 'a', 1, 'b', 2], f"got {result}"
def test_no_iterables():
"""no arguments yields nothing"""
assert list(interleave()) == []
def test_is_lazy():
"""returns an iterator, not a list"""
result = interleave('ab', 'cd')
assert iter(result) is result, "interleave should return an iterator"
Hints (3)
zipstops at the shortest input;zip_longestkeeps going and fills the gaps.- Use
missing = object()as thefillvalueso the filler can't be confused with real data such asNone, then skip it withis not. chain.from_iterable(rounds)flattens the tuples into one stream.
Show a solution
from itertools import zip_longest, chain
def interleave(*iterables):
missing = object() # a sentinel no real data can be equal to
rounds = zip_longest(*iterables, fillvalue=missing)
for item in chain.from_iterable(rounds):
if item is not missing:
yield itemExercise 3: Longest streak ✓ Passed
Write longest_streak(iterable) that returns a tuple (value, length) describing the longest run of consecutive equal items. If several runs are equally long, return the first one. For an empty iterable, return None.
For example, longest_streak('HHTTTHTTTTH') is ('T', 4).
from itertools import groupby
def longest_streak(iterable):
pass
def test_example():
"""coin flips"""
assert longest_streak('HHTTTHTTTTH') == ('T', 4), f"got {longest_streak('HHTTTHTTTTH')}"
def test_tie_first_wins():
"""ties go to the first run"""
assert longest_streak([1, 1, 2, 2, 3]) == (1, 2), f"got {longest_streak([1, 1, 2, 2, 3])}"
def test_not_global_count():
"""counts runs, not total occurrences"""
assert longest_streak('abababbb') == ('b', 3)
assert longest_streak('aabaab') == ('a', 2)
def test_generator_input():
"""works on a one-shot generator"""
assert longest_streak(x % 3 == 0 for x in [3, 6, 9, 1, 2]) == (True, 3)
def test_empty():
"""empty input returns None"""
assert longest_streak([]) is None
Hints (3)
groupbywithout a key yields one(value, group)pair per run of equal neighbors.- A group has no
len, butsum(1 for _ in group)counts it. max(..., key=..., default=None)handles the empty case, and returns the first of several equal maxima.
Show a solution
from itertools import groupby
def longest_streak(iterable):
runs = ((key, sum(1 for _ in group)) for key, group in groupby(iterable))
return max(runs, key=lambda run: run[1], default=None)Exercise 4: Sliding windows ✓ Passed
Write windows(iterable, n) that lazily yields every run of n consecutive items as a tuple, like a generalized pairwise. For example, list(windows([1, 2, 3, 4, 5], 3)) is [(1, 2, 3), (2, 3, 4), (3, 4, 5)].
It must accept any iterable (including infinite iterators), and yield nothing if there are fewer than n items. One approach: tee the input n times, advance the k-th copy by k items with islice, then zip the copies.
from itertools import tee, islice
def windows(iterable, n):
# your code here
pass
from itertools import count, islice
def test_example():
"""windows of size 3"""
assert list(windows([1, 2, 3, 4, 5], 3)) == [(1, 2, 3), (2, 3, 4), (3, 4, 5)]
def test_pairwise():
"""n=2 matches itertools.pairwise"""
from itertools import pairwise
assert list(windows('ABCD', 2)) == list(pairwise('ABCD'))
def test_too_short():
"""fewer than n items yields nothing"""
assert list(windows([1, 2], 3)) == []
def test_infinite():
"""works lazily on an infinite iterator"""
result = list(islice(windows(count(), 4), 2))
assert result == [(0, 1, 2, 3), (1, 2, 3, 4)], f"got {result}"
Hints (3)
tee(iterable, n)givesnindependent iterators over the same data.islice(copy, k, None)skips the firstkitems of a copy, lazily.zipof the shifted copies stops when the most-advanced copy runs out, which is exactly when the last full window has been produced.
Show a solution
from itertools import tee, islice
def windows(iterable, n):
copies = tee(iterable, n)
shifted = (islice(copy, k, None) for k, copy in enumerate(copies))
return zip(*shifted)