@@ -20,4 +20,48 @@ def square(s):
20
20
# furthermore, it can also be used as a shorthand
21
21
22
22
# so lets first look a simple usage of it to subsitute a function
23
- test
23
+ # this function squares a string then returns a string
24
+ square_string = lambda i : str (int (i ) ** 2 )
25
+ print (square_string ('5' ))
26
+
27
+ # the beauty of the implementation arises when you simply don't name it and apply it directly
28
+ print ((lambda i : str (int (i ) ** 2 ))('5' ))
29
+
30
+ # but can't we just use print(str(int('5') ** 2))?
31
+ # it is significantly more practical when used with map, filter and reduce!
32
+ # as you've seen earlier, map can be used to iterate the function over the entire iterable
33
+ # meanwhile filter does exactly what it sounds like it would do: filter items
34
+ # for example suppose you wanted to filter out any negative numbers
35
+ # you could simply use the following
36
+
37
+ print (list (filter (lambda i : i >= 0 , [- 5 , - 3 , 2 , 6 ])))
38
+
39
+ # this is equivalent to
40
+ output = []
41
+ for i in [- 5 , - 3 , 2 , 6 ]:
42
+ if i >= 0 :
43
+ output .append (i )
44
+ print (output )
45
+
46
+ # the last one is simply reduce, which iteratively sets the first term to the function of the first two terms
47
+ # eg the following produces the sum
48
+
49
+ from functools import reduce
50
+ print (reduce ((lambda a , b : a + b ), [- 5 , - 3 , 2 , 6 ]))
51
+
52
+ # this is equivalent to
53
+ sum = 0
54
+ for i in [- 5 , - 3 , 2 , 6 ]:
55
+ sum += i
56
+ print (sum )
57
+
58
+ # ACTIVITY: make an equivalent product function (there's no builtin product function for this)
59
+
60
+ # try the following problems:
61
+ # https://dmoj.ca/problem/ccc18j3
62
+ # https://dmoj.ca/problem/ccc15j3 (really long question)
63
+ # https://dmoj.ca/problem/ccc14s2 (hint: use tuples)
64
+
65
+ # code golf (shortest solution wins!)
66
+ # https://dmoj.ca/problem/ccc18j2
67
+ # https://dmoj.ca/problem/ccc16j2
0 commit comments