Practicing Coding Interview Questions in Python
Kirill Smirnov
Data Science Consultant, Altran
lambda expression/function - is a short function having the following syntax:
lambda arg1, arg2, ...: expression(arg1, arg2, ...)
lambda expression/function - is a short function having the following syntax:
lambda
lambda expression/function - is a short function having the following syntax:
lambda arg1, arg2, ...:
lambda expression/function - is a short function having the following syntax:
lambda arg1, arg2, ...: expression(arg1, arg2, ...)
lambda x: x**2
squared = lambda x: x**2
squared(4)
16
4
$\rightarrow$ x
$\rightarrow$ x**2
$\rightarrow$ 16
lambda expression/function - is a short function having the following syntax:
lambda arg1, arg2, ...: expression(arg1, arg2, ...)
power = lambda x, y: x**y
power(2, 3)
8
2, 3
$\rightarrow$ x, y
$\rightarrow$ x**y
$\rightarrow$ 8
power = lambda x, y: x**y
power(2)
TypeError
squared_lambda = lambda x: x**2
def squared_normal(x):
return x**2
lambda
def
squared_lambda = lambda
def squared_normal
squared_lambda = lambda x:
def squared_normal(x):
squared_lambda = lambda x: x**2
def squared_normal(x):
return x**2
squared_lambda(3)
9
squared_normal(3)
9
def function_with_callback(num, callback_function):
return callback_function(num)
callback_function(arg)
- a function with one argument
def squared_normal(x):
return x**2
function_with_callback(2, squared_normal)
4
def function_with_callback(num, callback_function):
return callback_function(num)
callback_function(arg)
- a function with one argument
--> def squared_normal(x): <--
--> return x**2 <--
--> function_with_callback(2, squared_normal) <--
4
def function_with_callback(num, callback_function):
return callback_function(num)
callback_function(arg)
- a function with one argument
function_with_callback(2, lambda x: x**2)
4
lambda expression/function - is a short function having the following syntax:
lambda arg1, arg2, ...: expression(arg1, arg2, ...)
lambda expression/function - is a short (anonymous) function having the following syntax:
lambda arg1, arg2, ...: expression(arg1, arg2, ...)
squared = lambda x: x**2
squared(3)
9
lambda expression/function - is a short (anonymous) function having the following syntax:
lambda arg1, arg2, ...: expression(arg1, arg2, ...)
(lambda x: x**2)(3)
9
def odd_or_even(num):
if num % 2 == 0:
return 'even'
else:
return 'odd'
odd_or_even(3)
'odd'
odd_or_even(6)
'even'
def odd_or_even(num):
return 'even' if num % 2 == 0 else 'odd'
odd_or_even(3)
'odd'
odd_or_even(6)
'even'
odd_or_even = lambda num: 'even' if num % 2 == 0 else 'odd'
odd_or_even(3)
'odd'
odd_or_even(6)
'even'
Use lambda expressions when it is really necessary!
Practicing Coding Interview Questions in Python