2
2

More than 3 years have passed since last update.

【Python3.8〜】lambda式でスマートに再帰関数を定義する方法

Last updated at Posted at 2020-11-05

はじめに

lambda式でも再帰を使いたいことありますよね(主にネタコードで)。
Python3.8以降ならスッキリかけます。
フィボナッチ数列のx番目を求める関数で比較してみましょう。

方法

〜Python3.7

print((lambda x: (lambda f, x: f(f, x))(lambda f, x: f(f, x-1)+f(f, x-2) if x > 2 else 1, x))(10))
# >> 55

Python3.8〜

print((self:=lambda x:self(x-1) + self(x-2) if x > 2 else 1)(10))
# >> 55

す ご く す っ き り

2
2
14

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2