@rasca0027
kelly.chang@nyu.edu
Turing Complete:
it is a universal model of computation that can be used to simulate any Turing machine
Also called: Anonymous function
def addition(a, b):
return a + b
>>> addition(1, 3)
>>> 4
add = lambda a, b: a + b
>>> add(1, 2)
>>> 3
map(function, sequence)
def plus(x):
return x + 1
map(plus, range(3))
>>> [1, 2, 3]
map(lambda x: x + 1, range(3))
>>> [1, 2, 3]
def f(x):
return x % 2 == 0
filter(f, range(10))
>>> [0, 2, 4, 6, 8]
filter(lambda x: x % 2 == 0, range(10))
>>> [0, 2, 4, 6, 8]
price = '3,450 元'
filter(lambda x: x.isdigit(), price)
>>> 3450filter(function, sequence)
"The technique of transforming a function that takes multiple arguments in such a way that it can be called as a chain of functions each with a single argument"
def comp(threshold):
return lambda x: x < threshold
>>> comp
<function comp at 0x10703e048>
>>> comp(10)
<function comp.<locals>.<lambda> at 0x10703e1e0>
>>> f = comp(10)
>>> f(1)
True
>>> func_a = comp(10)
>>> func_b = comp(20)
>>> print(func_a(5), func_a(8), func_a(13), func_a(21))
True True False Falsewith functools and lambda
def add(x, y):
return x + y
add(5)
>>> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: add() takes exactly 2 arguments (1 given)
# try using functool
from functools import partial
f = partial(add, y=3)
f(2)
>>> 5
# using lambda
def example(a, b, c):
return (a, b, c)
curried1 = lambda b, c: example(1, b, c)
curried1(2, 3)
>>> (1, 2, 3)