Exercises
itertools
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Flatten the groups into one list without building an intermediate list.
Python
groups = [[1, 2], [3], [4, 5]]
# print [1, 2, 3, 4, 5]
chain.from_iterable takes an iterable of iterables.
from itertools import chain
groups = [[1, 2], [3], [4, 5]]
print(list(chain.from_iterable(groups)))Exercise 2Passed
Take the first five numbers from an endless counter.
Python
from itertools import count
# print [1, 2, 3, 4, 5]
You cannot slice a generator, but islice can.
from itertools import count, islice
print(list(islice(count(1), 5)))Exercise 3Passed
Print the difference between each pair of neighbouring readings.
Python
readings = [10, 12, 11, 15]
# print [2, -1, 4]
pairwise gives you each neighbouring pair.
from itertools import pairwise
readings = [10, 12, 11, 15]
print([b - a for a, b in pairwise(readings)])