From loops to pipelines via $\mathrm{map}$, $\mathrm{filter}$, and folds
$$ R = \sum_{\substack{1\le k\le 10\\ k\ \mathrm{odd}}} k^2 $$
[1, 2, 3, 4][[1, 2], 3, 4]my_map(f, s) = [f(x) for x in s]list(map(lambda x: x * x, [1, 2, 3, 4]))list(map(lambda x: x + 10, [1, 2, 3]))[11, 12, 13] (each element gets 10 added: 1→11, 2→12, 3→13)my_filter(p, s) = [x for x in s if p(x)]list(filter(lambda x: x % 2 == 0, range(10)))list(filter(lambda x: x > 3, [1, 5, 2, 7, 3]))[5, 7] — why is 3 excluded when the test is x > 3?$$ \operatorname{fold\text{-}right}(\oplus, z, [a_1,\dots,a_n]) = a_1 \oplus (a_2 \oplus (\cdots \oplus (a_n \oplus z))) $$
from functools import reduce (behaves like fold-left)sum(map(lambda x: x*x, filter(lambda x: x%2==1, range(1, 11))))sum([x*x for x in range(1, 11) if x % 2 == 1])def naturals(): n = 0 while True: yield n n += 1filter and map can stay lazy until sum
Powered by SciMigo AI Tutor - https://scimigo.com