Converting functions to lambda expressions
Convert these three normally defined functions into lambda expressions:
# Returns a bigger of the two numbers
def func1(x, y):
if x >= y:
return x
return y
# Returns a dictionary counting characters in a string
def func2(s):
d = dict()
for c in set(s):
d[c] = s.count(c)
return d
# Returns a squared root of a sum of squared numbers
def func3(*nums):
squared_nums = [n**2 for n in nums]
sum_squared_nums = sum(squared_nums)
return math.sqrt(sum_squared_nums)
This exercise is part of the course
Practicing Coding Interview Questions in Python
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Convert func1() to a lambda expression
lambda1 = ____
print(str(func1(5, 4)) + ', ' + str(lambda1(5, 4)))
print(str(func1(4, 5)) + ', ' + str(lambda1(4, 5)))