-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctions-LAMBDA.py
More file actions
166 lines (116 loc) · 4.2 KB
/
Functions-LAMBDA.py
File metadata and controls
166 lines (116 loc) · 4.2 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
########## LAMBDA ##########
# The lambda function is a concept borrowed from mathematics, more specifically, from a part called the Lambda calculus
# Mathematicians use the Lambda calculus in many formal systems connected with logic, recursion, or theorem provability
# Programmers use the lambda function to simplify the code, to make it clearer and easier to understand
# lambda function is a function without a name
# It's not a problem, as we can name such a function if we really need, but in many cases the lambda function
# can exist and work while remaining fully incognito
# lambda function accept any number of argument(s)
# BUT lambda function can evaluate ONLY 1 expression
two = lambda: 2
sqr = lambda x: x * x
pwr = lambda x, y: x ** y
for a in range(-2, 3):
print(sqr(a), end=" ")
print(pwr(a, two()))
# 4 4
# 1 1
# 0 0
# 1 1
# 4 4
## Why parentheses after two ?
# two = function
# two() = calls the function with a parameter, here 2, and returns a value
two = lambda: 2 # the function
print(two)
# <function <lambda> at 0x000001AE9EAA8C20> ==> function memory id
print(two())
# 2 ==> retrun from the function
## lambda DOES NOT ACCEPT RETURN
# Lambda functions are single expressions, and return is not allowed inside them
lambda x, y: return x + y
# Correct way:
lambda x, y: x + y
## Usage cases
def print_function(args, fun):
for x in args:
print('f(', x,')=', fun(x), sep='')
def poly(x):
return 2 * x**2 - 4 * x + 2
print_function([x for x in range(-2, 3)], poly)
# f(-2)=18
# f(-1)=8
# f(0)=2
# f(1)=0
# f(2)=2
## mixing lambda and function
def f(a, b):
return a(b)
# function f takes 2*arguments: a (a function) and b (a value)
print(f(lambda x: x and True, 1 > 0))
# ==> evaluates x and True for x = 1>0, = True, True and True = True
# True
## cas d'erreur
def f(a, b):
return b(b) # TypeError: 'int' object is not callable
print(f(lambda x: x + 1, 0))
# TypeError: 'int' object is not callable
## LAMBDA + map()
# map() # Returns the specified iterator with the specified function applied to each item
map(function, list)
# takes minimum two arguments but map() can accept more than two arguments:
# - a function
# - a list
# the second map() argument may be any entity that can be iterated: a tuple, or just a generator
# map() applies the function passed by its first argument to all its second argument's elements
# and returns an iterator delivering all subsequent function results
# We can use the resulting iterator in a loop, or convert it into a list using the list() functionl
def myfunc(n):
return len(n)
x = map(myfunc, ('apple', 'banana', 'cherry'))
print(x)
# <map object at 0x056D44F0>
print(list(x)) #convert the map into a list, for readability:
# [5, 6, 6]
letters = ["beach", "car"]
funified = list(map(lambda word: f"{word} is fun!", letters))
# This part is an anonymous function (lambda)
# It takes 1*argument and returns a new character chain
print(funified)
# ['beach is fun!', 'car is fun!']
list_1 = [x for x in range(5)]
print(list_1)
# [0, 1, 2, 3, 4]
list_2 = list(map(lambda x: 2 ** x, list_1))
print(list_2)
# [1, 2, 4, 8, 16]
for x in map(lambda x: x * x, list_2):
print(x, end=' ')
# 1 4 16 64 256
## LAMBDA + filter()
from random import seed, randint
seed() # cf random module
data = [randint(-10,10) for x in range(5)]
filtered = list(filter(lambda x: x > 0 and x % 2 == 0, data))
print(data)
# [-6, 8, 0, -1, 9]
print(filtered)
# [8]
my_tuple = (0, 1, 2, 3, 4, 5, 6)
foo = tuple(filter(lambda x: x > 1, my_tuple))
print(foo)
# (2, 3, 4, 5, 6)
my_tuple = (0, 1, 2, 3, 4, 5, 6)
foo = tuple(filter(lambda x: x-0 and x-1, my_tuple))
print(foo)
# (2, 3, 4, 5, 6)
numbers = [i*i for i in range(5)] # 1. create a list
foo = list(filter(lambda x: x % 2, numbers)) # 2. Filter odd numbers
print(foo) # 3. Print the result
# [1,9]
# for each x in numbers :
# x = 0 → lambda 0: 0 % 2 → 0 → falsy → ❌ rejected
# x = 1 → lambda 1: 1 % 2 → 1 → truthy → ✅ kept
# x = 4 → lambda 4: 4 % 2 → 0 → falsy → ❌ rejected
# x = 9 → lambda 9: 9 % 2 → 1 → truthy → ✅ kept
# x = 16 → lambda 16: 16 % 2 → 0 → falsy → ❌ rejected