v9.1.1
Menu

Higher-Order Functions

mediumFREEFunctionsPython FunctionalPython Foundations

Problem Statement

Use map, filter, and reduce to process data.

Background

Python provides functional programming tools:

  • map(func, iterable) - apply function to each element
  • filter(func, iterable) - keep elements where func returns True
  • reduce(func, iterable) - combine elements pairwise (from functools)

Your Task

Write a function process_numbers(numbers) that applies various higher-order functions.

Output Format

Return a dictionary with:

  • "doubled": All numbers doubled (use map)
  • "evens": Only even numbers (use filter)
  • "product": Product of all numbers (use reduce)
  • "sum_of_squares": Sum of squared numbers (use map+reduce)

Example

Input
[1, 2, 3, 4, 5]
Output
{'doubled': [2, 4, 6, 8, 10], 'evens': [2, 4], 'product': 120, 'sum_of_squares': 55}
Reasoning
  • Input: numbers is a list of integers, here x=(1,2,3,4,5)x = (1, 2, 3, 4, 5). Each of the four outputs reads the same list independently; none builds on another.
  • doubled: every element scaled by 2, keeping order and length: 2xi2x_i gives [2, 4, 6, 8, 10]. Five numbers in, five out.
  • evens: only the elements with xi mod 2=0x_i \bmod 2 = 0 survive, unchanged. From the original list that is [2, 4]. Notice these are the original values, not the doubled ones (every doubled value would be even).
  • product: fold the list into one number by multiplying pairwise: ((((1⋅2)⋅3)⋅4)⋅5)=120((((1 \cdot 2) \cdot 3) \cdot 4) \cdot 5) = 120, i.e. ∏ixi=5!\prod_i x_i = 5!.
  • sum_of_squares: square each element, (1,4,9,16,25)(1, 4, 9, 16, 25), then fold by addition: ∑ixi2=55\sum_i x_i^2 = 55.
  • Output: a dictionary with exactly these four keys in this order, two lists and two integers. For an all-odd input such as (1,3,5)(1, 3, 5), evens is the empty list [].

Constraints

  • Use map, filter, and reduce from functools
  • Numbers list will have at least 1 element

Learn this in

More from Python Foundations

solution.py

Test results

Sign in to run your code against the test cases.