开始使用免费开始使用

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)

本练习是课程的一部分

Practicing Coding Interview Questions in Python

查看课程

交互式实操练习

通过完成这段示例代码来试试这个练习。

# 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)))
编辑并运行代码