1
0

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 3 years have passed since last update.

Python 3.8: 代入式(:=)を使って、フィボナッチ数列の lambda 式を作る

Last updated at Posted at 2021-08-26

フィボナッチ数列は単純な手続きで作れるけど、プログラムにすると以外と面倒臭い。

Python
def fibonacci_table(n):
    r = []
    a, b = 0, 1
    for _ in range(n):
        r.append(a)
        a, b = b, a + b
    return r

これを Python 3.8 から使用可能な代入式 := を使って lambda 式で作ってみる。

Python3.8
fibonacci_table = lambda n, f1=0, f2=1, f3=1: ([0, 1] + [(f3 := f1 + f2, f1 := f2, f2 := f3)[0] for _ in range(n - 2)])[:n]

もっと単純になるかと思ったけど、横に長くなっただけだった。
(行末の [:n] は、n が 0 または 1 のためにあります)

実行結果
>>> fibonacci_table(12)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

@shiracamus さんに教えてもらった記事をここにも貼っておきます。

1
0
5

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?