def f(x):
return x**2
f(3)
g = lambda x: x**2
g
g(3)
(lambda x: x**2)(3)
(lambda x, y: x**2 + y)(3, 10)
from scipy.integrate import quad
quad(f, 0, 2)
quad(lambda x: x**4, 0, 2)
import math
quad(math.sin, 0, 2)
quad(lambda x: math.sin(x) * math.cos(x), 0, 2)
f(2)
map(f, [0, 1, 3, 4, 5, 100, -3, 42])
map(lambda x: x**2, [0, 1, 3, 4, 5, 100, -3, 42])
[f(x) for x in [0, 1, 3, 4, 5, 100, -3, 42]]
[x**2 for x in [0, 1, 3, 4, 5, 100, -3, 42]]
def is_positive(n):
return n > 0
is_positive(1)
filter(is_positive, [1, -2, -3, 4, 10])
filter(lambda x: x > 0, [1, -2, -3, 4, 10])
[x for x in [1, -2, -3, 4, 10] if x > 0]
def f(x, y):
print("Called with x={} and y={}".format(x, y))
return x + y
reduce(f, [1, 2, 3, 4], 0)
reduce(f, "test", "X")
%loadpy closure_adder42.py
def make_add42():
def add42(x):
return x + 42
return add42
# add42 = make_add42()
# print(add42(2)) # output is '44'
f1 = make_add42()
f2 = make_add42()
id(f1)
id(f2)
f1
f2
%loadpy closure_adder.py
import math
def make_adder(y):
def adder(x):
return x + y
return adder
add42 = make_adder(42)
addpi = make_adder(math.pi)
# print(add42(2)) # output is 44
# print(addpi(-3)) # output is 0.14159265359
add42(2)
addpi(1)