15
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Python】lambdaで再帰

Last updated at Posted at 2017-11-01

lambda式の中で再帰がしたい。できるだけ短く書きたい。

できるのか

参考文献:

自分自身を引数で受け取る関数を使えばいいらしい。なるほど。

>>> gcd = lambda *x: (lambda f: f(f, *x))(lambda f, x, y: f(f, y, x % y) if y else x)
>>> gcd(24, 9)  # 最大公約数
3

PEP8準拠での文字数は、本体 (lambda f, x, y: ...) の文字数 + 33文字。

短くなるのか

キーワード引数を使ったら、lambdaが1つ減って短くなった。(本体 + 25文字)

>>> gcd = lambda *x, f=(lambda f, x, y: f(f, y, x % y) if y else x): f(f, *x)
>>> gcd(24, 9)
3

追記: キーワード引数のカッコは省略できた。(本体 + 23文字)

>>> gcd = lambda *x, f=lambda f, x, y: f(f, y, x % y) if y else x: f(f, *x)
>>> gcd(24, 9)
3

おわりに

Pythonのキーワード引数はトリッキーな使い方ができて面白いですね。
もっと短くなる書き方があれば教えてください。

15
17
1

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
15
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?