Skip to content
Foxipa
Code Completion 5 Challenges

Complete the itertools code

Practice flattening, limiting, batching, grouping consecutive records, and building combinations with itertools.

Intermediate ~11 min read

Challenge 1

Combine the inner lists into one stream and print the names in their original order.

python Your answer
from itertools import chain

teams = [["Iris", "Omar"], ["Bo"]]
names = list()
print(names)

Press Ctrl⌘Enter to check your answer

Challenge 2

Take four values from this infinite sequence, beginning at 5 and increasing by 3.

python Your answer
from itertools import count, islice

values = list()
print(values)

Press Ctrl⌘Enter to check your answer

Challenge 3

Produce each running maximum rather than the running sum.

python Your answer
from itertools import accumulate

values = [4, 1, 7, 2]
result = list()
print(result)

Press Ctrl⌘Enter to check your answer

Challenge 4

Generate all two-person teams, treating the order of names as irrelevant.

python Your answer
from itertools import combinations

people = ["Mia", "Leo", "Ari"]
teams = list()
print(teams)

Press Ctrl⌘Enter to check your answer

Challenge 5

The records are sorted by department. Group consecutive records with the same department and print each group’s names.

python Your answer
from itertools import groupby
from operator import itemgetter

records = [("design", "Amina"), ("design", "Leo"), ("support", "Omar"), ("support", "Maya")]
for department, entries in :
    names = [name for _, name in entries]
    print(f"{department}: {', '.join(names)}")

Press Ctrl⌘Enter to check your answer