22
33``` python
44def sum_of_multiples (limit , factors ):
5- is_multiple = lambda n : any (n % f == 0 for f in factors if f != 0 )
6- return sum (filter (is_multiple, range (limit)))
5+ return sum (filter (
6+ lambda n : any (n % f == 0 for f in factors if f != 0 ),
7+ range (limit)
8+ ))
79```
810
911Probably the most straightforward way of solving this problem is to
@@ -44,9 +46,11 @@ Had the highlighted solution not used `sum`, it might have looked like this:
4446
4547``` python
4648def sum_of_multiples (limit , factors ):
47- is_multiple = lambda n : any (n % f == 0 for f in factors if f != 0 )
49+ multiples = filter (
50+ lambda n : any (n % f == 0 for f in factors if f != 0 ),
51+ range (limit))
4852 total = 0
49- for multiple in filter (is_multiple, range (limit)) :
53+ for multiple in multiples :
5054 total += multiple
5155 return total
5256```
@@ -103,7 +107,9 @@ The main differences between containers (such as `list`s) and iterators are
103107To illustrate the latter difference:
104108
105109``` python
106- is_even = lambda n : n % 2 == 0
110+ def is_even (n ):
111+ return n % 2 == 0
112+
107113numbers = range (20 ) # 0, 1, …, 19
108114even_numbers = filter (is_even, numbers) # 0, 2, …, 18
109115sum (numbers) # ⟹ 190
@@ -126,7 +132,9 @@ Had the highlighted solution not used `filter`, it might have looked like this:
126132
127133``` python
128134def sum_of_multiples (limit , factors ):
129- is_multiple = lambda n : any (n % f == 0 for f in factors if f != 0 )
135+ def is_multiple (n ):
136+ return any (n % f == 0 for f in factors if f != 0 )
137+
130138 multiples = [candidate for candidate in range (limit) if is_multiple(candidate)]
131139 return sum (multiples)
132140```
@@ -193,13 +201,25 @@ list(filter(
193201# ⟹ ['b', 'dd', 'eee']
194202```
195203
204+ ~~~~ exercism/note
205+ Immediately applying a lambda expression is possible, but generally pointless:
206+
207+ ```python
208+ # Instead of
209+ (lambda a, b, x: a * x + b)(2, 3, y)
210+ # you might as well write
211+ 2 * y + 3
212+ ```
213+ ~~~~
214+
215+ ~~~~ exercism/caution
216+ Assigning a lambda expressions to variables is unidiomatic.
217+ When you want to give a lambda expression a name, use `def` instead.
218+ ~~~~
219+
196220Only functions that can be defined using a single (` return ` ) statement can be written as a lambda expression.
197221If you need multiple statements, you have no choice but to use ` def ` .
198222
199- The solution highlighted above assigns a lambda expression to a variable: ` is_multiple ` .
200- Some people consider this to be unidiomatic and feel one should always use ` def ` when a function is to have a name.
201- A lambda expression is used here anyway to demonstrate the feature, and also because the author prefers its compactness.
202-
203223Had the highlighted solution not used ` lambda ` , it might have looked like this:
204224
205225``` python
0 commit comments