All quizzesHard
Composition & Closures — Series 2
Preview — 3 of 10 questions
What is the output of the following code?
javascript
from itertools import groupby
data = [("a", 1), ("a", 2), ("b", 3), ("b", 4)]
groups = list(groupby(data, key=lambda x: x[0]))
result = []
for key, group in groups:
result.append((key, list(group)))
print(result)A[('a', [('a', 1), ('a', 2)]), ('b', [('b', 3), ('b', 4)])]
B[('a', []), ('b', [])]
C[('a', [('a', 1), ('a', 2)]), ('b', [])] — only the last group ends up exhausted.
DTypeError: group object already consumed
What is the output of the following code?
javascript
def make_checkers():
def is_even(n):
if n == 0:
return True
return is_odd(n - 1)
def is_odd(n):
if n == 0:
return False
return is_even(n - 1)
return is_even, is_odd
is_even, is_odd = make_checkers()
print(is_even(10))
print(is_odd(10))
print(is_even(7))ATrue, True, False
BNameError: name 'is_odd' is not defined — is_even can't reference is_odd before it's been defined.
CRecursionError: maximum recursion depth exceeded
DTrue, False, False
What is the output of the following code?
javascript
cache = {}
def memoize(func):
def wrapper(arg):
if arg not in cache:
cache[arg] = func(arg)
return cache[arg]
return wrapper
@memoize
def process(data):
return sum(data)
print(process((1, 2, 3)))
process([1, 2, 3])A6, then TypeError: cannot use 'list' as a dict key (unhashable type: 'list')
B6, then 6 — the cache silently converts the list to a tuple before checking membership.
CTypeError on the very first call already, since (1, 2, 3) and [1, 2, 3] can't both be used with the same cache.
D6, then None — a cache miss for an unhashable argument silently returns None instead of raising.
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.