itertools & partial — Series 2

Preview — 3 of 10 questions

What is the output of the following code?

javascript
from itertools import compress

data = ["a", "b", "c", "d", "e"]
selectors = [1, 0, 1, 0, 1]
result = list(compress(data, selectors))
print(result)
A['b', 'd']
B['a', 'b', 'c']
C[1, 0, 1, 0, 1]
D['a', 'c', 'e']

What is the output of the following code?

javascript
from itertools import dropwhile, takewhile

nums = [1, 3, 5, 8, 2, 6, 9]
print(list(takewhile(lambda x: x % 2 == 1, nums)))
print(list(dropwhile(lambda x: x % 2 == 1, nums)))
A[1, 3, 5], then [8, 2, 6, 9]
B[1, 3, 5, 9], then [8, 2, 6] — both functions scan the entire iterable, collecting every element that matches (or doesn't), regardless of position.
C[1, 3, 5, 8, 2, 6, 9], then [] — takewhile takes everything and dropwhile drops everything.
D[1, 3, 5], then [8, 2, 6] — dropwhile stops as soon as it finds another odd number.

What is the output of the following code?

javascript
from itertools import combinations, combinations_with_replacement

items = ['A', 'B', 'C']
print(list(combinations(items, 2)))
print(list(combinations_with_replacement(items, 2)))
A[('A', 'B'), ('A', 'C'), ('B', 'C')], then the exact same result — combinations_with_replacement is just an alias for combinations.
B[('A', 'B'), ('A', 'C'), ('B', 'C')], then [('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]
C[('A', 'A'), ('B', 'B'), ('C', 'C')], then [('A', 'B'), ('A', 'C'), ('B', 'C')] — swaps which function produces which result.
D[('A', 'B'), ('A', 'C'), ('B', 'C')], then [('A', 'B'), ('B', 'C'), ('C', 'A')]

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.