itertools & functools — lru_cache, product, groupby & reduce — Concept Check
Questions on itertools & functools — lru_cache, product, groupby & reduce. @lru_cache memoizes recursion in one decorator line; itertools generates combinations, permutations and products lazily — brute-force search and DP speedups for free.
Questions in this quiz
8 questions on itertools & functools — lru_cache, product, groupby & reduce — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.You have a recursive function to calculate Fibonacci numbers. How can you optimize it using functools?
- AUse itertools.groupby for grouping
- BUse functools.reduce for accumulation
- CUse itertools.product for combinations
- DUse @lru_cache to memoize results
2.A developer needs to generate all possible orderings of a list of items. Which itertools function should they use?
- Apermutations
- Bcombinations
- Cproduct
- Dgroupby
3.Your function is running slowly due to repeated calculations. What can you do to improve its performance?
- AUse itertools.chain to merge results
- BDecorate with @lru_cache to cache results
- CUse functools.partial to pre-fill arguments
- DApply itertools.accumulate to sum results
4.Which of the following is true about itertools.groupby?
- AIt creates a Cartesian product of lists
- BIt generates all subsets of a list
- CIt groups all identical items regardless of position
- DIt groups consecutive equal items
5.A developer uses functools.reduce to sum a list of numbers. What is a potential downside of this approach?
- AIt requires the list to be sorted
- BIt's less readable than a loop
- CIt modifies the original list
- DIt only works with integers
6.You need to create a Cartesian product of two lists. Which itertools function is appropriate?
- Apermutations
- Bcombinations
- Cproduct
- Daccumulate
7.Which statement about functools.partial is correct?
- AIt groups consecutive items
- BIt pre-fills arguments for a function
- CIt caches results of function calls
- DIt generates combinations of a list
8.A developer wants to generate all possible subsets of a list. Which itertools function should they use?
- Apermutations
- Bchain with combinations
- Cgroupby
- Dreduce