
Code
map, filter & reduce
Three classic tools apply a function across a collection:
from functools import reduce
nums = [4, -1, 3, -7]
list(map(abs, nums)) # [4, 1, 3, 7]
list(filter(lambda n: n > 0, nums)) # [4, 3]
reduce(lambda a, b: a + b, nums, 0) # -1
map(func, items)callsfuncon every item.filter(func, items)keeps items wherefuncreturns something truthy.reduce(func, items, start)folds everything into one value:((0 + 4) + -1) + .... Thestartvalue is used for empty inputs.
map and filter are lazy: they hand back an iterator that
produces values on demand, so wrap them in list() to see them all.
Often a comprehension reads better ([n for n in nums if n > 0]), but
map is lovely when you already have a function: map(str.strip, lines).
These tools work best with pure functions: functions whose result depends only on their arguments and that don't change anything outside themselves. Pure functions are easy to test, reuse and combine.
Assignment
Use the tool named in each step:
clean_names(names): withmap, strip spaces and title-case each name (" ada lovelace "becomes"Ada Lovelace"). Return a list.positives(nums): withfilter, keep numbers above 0. Return a list.product(nums): withreduce, multiply all numbers together. An empty list gives1.
Use the tool named in each step:
clean_names(names): withmap, strip spaces and title-case each name (" ada lovelace "becomes"Ada Lovelace"). Return a list.positives(nums): withfilter, keep numbers above 0. Return a list.product(nums): withreduce, multiply all numbers together. An empty list gives1.
main.py Python sleeping
Press Run to try your code, then Check to test it.