All quizzesHard
Advanced FP Patterns — Series 3
Preview — 3 of 10 questions
What is the output of the following code?
javascript
from itertools import groupby, chain
data = [("a", 1), ("a", 2), ("b", 3), ("b", 4), ("a", 5)]
grouped = {k: [v for _, v in g] for k, g in groupby(data, key=lambda pair: pair[0])}
print(grouped)
flattened = list(chain.from_iterable(grouped.values()))
print(flattened)A{'a': [5], 'b': [3, 4]}, [5, 3, 4]
B{'a': [1, 2, 5], 'b': [3, 4]}, [1, 2, 5, 3, 4]
C{'a': [1, 2], 'b': [3, 4]}, [1, 2, 3, 4]
D{'a': [5], 'b': [3, 4]}, [3, 4, 5]
What is the output of the following code?
javascript
import operator
words = [" hello ", " world "]
strip_call = operator.methodcaller("strip")
print(list(map(strip_call, words)))
replace_call = operator.methodcaller("replace", "o", "0")
print(list(map(replace_call, ["hello", "world"])))A['hello', 'world'], ['hello', 'world']
B['hello', 'world'], ['hell0', 'w0rld']
C[' hello ', ' world '], ['hell0', 'w0rld']
D['hello', 'world'], TypeError: methodcaller() takes 1 positional argument but 3 were given
What is the output of the following code?
javascript
import functools
def memoize_by(key_func):
def decorator(func):
cache = {}
@functools.wraps(func)
def wrapper(*args):
k = key_func(*args)
if k not in cache:
print(f"computing for key {k}")
cache[k] = func(*args)
return cache[k]
return wrapper
return decorator
@memoize_by(lambda a, b: (min(a, b), max(a, b)))
def combine(a, b):
return f"{a}-{b}"
print(combine(1, 2))
print(combine(2, 1))
print(combine(3, 4))Acomputing for key (1, 2), 1-2, 2-1, computing for key (3, 4), 3-4
Bcomputing for key (1, 2), 1-2, 1-2, 1-2
Ccomputing for key (1, 2), 1-2, 1-2, computing for key (3, 4), 3-4
Dcomputing for key (1, 2), 1-2, computing for key (2, 1), 2-1, computing for key (3, 4), 3-4
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.