0
0

はじめに

  • リスト内包表記の第3弾
  • if文の条件分岐を入れ子にしたときのリスト内包表記を実現してみる

トリボナッチ数列とは

  • 初項$a_1 = 0$,第2項$a_2 = 0$,第3項$a_3 = 1$の数列

  • 以下のようなイメージ

    トリボナッチ.PNG

for 文を用いた表現

l = []
for i in range(10):
    if i > 2:
        l.append(l[len(l)-1]+l[len(l)-2]+l[len(l)-3])
    else:
        if i > 1:
            l.append(1)
        else:
            l.append(0)

リスト内包表記を用いた実装

リスト内包表記でif文を入れ子にすることも可能

l = []
[l.append(l[len(l)-1]+l[len(l)-2]+l[len(l)-3]) if i > 2 else (l.append(1) if i > 1 else l.append(0)) for i in range(10)]

実行結果

  • print(l)を実行すると以下のようになる
[0, 0, 1, 1, 2, 4, 7, 13, 24, 44]
0
0
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
0
0