関数をラムダ式に書き換える
次の3つの通常の関数定義を、ラムダ式に書き換えてください。
# 2つの数のうち大きい方を返す
def func1(x, y):
if x >= y:
return x
return y
# 文字列内の文字数を数える辞書を返す
def func2(s):
d = dict()
for c in set(s):
d[c] = s.count(c)
return d
# 複数の数を二乗して合計し、その平方根を返す
def func3(*nums):
squared_nums = [n**2 for n in nums]
sum_squared_nums = sum(squared_nums)
return math.sqrt(sum_squared_nums)
この演習はコースの一部です
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)))