forked from subsr97/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmake-functions.py
98 lines (74 loc) · 1.59 KB
/
make-functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
"""
#188
Google
This problem was asked by Google.
What will this code print out?
def make_functions():
flist = []
for i in [1, 2, 3]:
def print_i():
print(i)
flist.append(print_i)
return flist
functions = make_functions()
for f in functions:
f()
How can we make it print out what we apparently want?
"""
def make_functions():
flist = []
for i in [1,2,3]:
def print_i():
print(i)
flist.append(print_i)
return flist
def make_functions_modified():
flist = []
for i in [1,2,3]:
def print_i(i=i):
print(i)
flist.append(print_i)
return flist
def make_lambdas():
llist = []
for i in [1,2,3]:
llist.append(lambda i=i: print(i))
return llist
def main():
functions = make_functions()
for f in functions:
f()
"""
Output:
3
3
3
Explanation:
The variable i in line 31 refers to the variable i in the outer scope (i.e) line 29.
"""
print()
functions = make_functions_modified()
for f in functions:
f()
"""
Output:
1
2
3
Explanation:
Pass i as an argument to the print_i() function so that the i in line 31 will refer to that parameter rather than the outer i.
"""
print()
lambdas = make_lambdas()
for l in lambdas:
l()
"""
Output:
1
2
3
Explanation:
Use lambdas to achieve the same functionality using anonymous functions.
"""
if __name__ == "__main__":
main()