Higher-order functionshigher-order-filter-map
LessonΒ·difficulty 2/5Β·~12 min
Higher-order: filter then map
Higher-order: filter then map
A higher-order function takes another function as an argument. Two classics
are filter (keep items that pass a test) and map (transform every item):
python
nums = [1, -2, 3]
filter(lambda n: n > 0, nums) # keeps 1 and 3
map(lambda n: n * n, nums) # squares each item
list(...) # both are lazy β wrap in list() to see values
Chaining them is a clean pipeline: first filter the data, then map a transform over what survives.
Your task
Write positives_squared(nums) that keeps only the strictly positive
numbers, then squares them, using filter() and map(). Return a list.
python
positives_squared([-2, -1, 0, 3, 4]) # [9, 16]
positives_squared([1, 2, 3]) # [1, 4, 9]
positives_squared([-5]) # []
Hint: kept = filter(lambda n: n > 0, nums), then
list(map(lambda n: n * n, kept)).
Tests
- mixed signs
- all positive
- single negative
- empty list
- zero excluded (hidden)
- order preserved (hidden)
Stuck? Ask for a spark
warming up
Loading editorβ¦
$ Console output will appear here.