Help us understand the problem. What is going on with this article?

【Python】lambdaで再帰

More than 1 year has passed since last update.

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

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away