4
3

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でFizzBuzzいろいろ

Posted at

###配列に結果を格納し、出力する方式を採用
動作確認はこちらのサイトを使いました

こんな感じで出力されていればOK
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']
1.一般的なFizzBuzz
fizzbuzz = []

for i in range(1, 16):
    if i % 15 == 0:
        fizzbuzz.append('FizzBuzz')
    elif i % 3 == 0:
        fizzbuzz.append('Fizz')
    elif i % 5 == 0:
        fizzbuzz.append('Buzz')
    else:
        fizzbuzz.append(str(i))

print(fizzbuzz)
2.関数と化したFizzBuzz
fizzbuzz = []

def get_fizzbuzz(i):
    if i % 15 == 0:
        return 'FizzBuzz'
    elif i % 3 == 0:
        return 'Fizz'
    elif i % 5 == 0:
        return 'Buzz'
        
    return str(i)

for i in range(1, 16):
    fizzbuzz.append(get_fizzbuzz(i))

print(fizzbuzz)
3.ループ内で関数定義することも可能
fizzbuzz = []

for i in range(1, 16):
    # その場しのぎ的な?
    def get_fizzbuzz(i):
        if i % 15 == 0:
            return 'FizzBuzz'
        elif i % 3 == 0:
            return 'Fizz'
        elif i % 5 == 0:
            return 'Buzz'
        
        return str(i)

    fizzbuzz.append(get_fizzbuzz(i))

print(fizzbuzz)
4.ラムダ式と化したFizzBuzz
fizzbuzz = []

get_fizzbuzz = lambda i: 'FizzBuzz' if i % 15 == 0 else 'Fizz' if i % 3 == 0 else 'Buzz' if i % 5 == 0 else str(i)

for i in range(1, 16):
    # [3.]と同じように ラムダ式はここに書いてもOK
    # get_fizzbuzz = lambda i: 'FizzBuzz' if i % 15 == 0 else 'Fizz' if i % 3 == 0 else 'Buzz' if i % 5 == 0 else str(i)
    fizzbuzz.append(get_fizzbuzz(i))

print(fizzbuzz)
5.三項演算と化したFizzBuzz
fizzbuzz = []

for i in range(1, 16):
    fizzbuzz.append('FizzBuzz' if i % 15 == 0 else 'Fizz' if i % 3 == 0 else 'Buzz' if i % 5 == 0 else str(i))

print(fizzbuzz)
6.リスト内包表記と化したFizzBuzz
fizzbuzz = ['FizzBuzz' if i % 15 == 0 else 'Fizz' if i % 3 == 0 else 'Buzz' if i % 5 == 0 else str(i) for i in range(1, 16)]

print(fizzbuzz)
7.ワンライナーと化したFizzBuzz
print(['FizzBuzz' if i % 15 == 0 else 'Fizz' if i % 3 == 0 else 'Buzz' if i % 5 == 0 else str(i) for i in range(1, 16)])

###ラムダ式もリスト内包表記も結局は三項演算

この記法を覚えることが重要?
'FizzBuzz' if i % 15 == 0 else 'Fizz' if i % 3 == 0 else 'Buzz' if i % 5 == 0 else str(i)
javascriptでこう書いているのと同じ
i % 15 === 0 ? 'FizzBuzz' : i % 3 === 0 ? 'Fizz' : i % 5 === 0 ? 'Buzz' : String(i)

// 参考:javascriptでワンライナー
console.log([...Array(15)].map((v, i) => (i => i % 15 === 0 ? 'FizzBuzz' : i % 3 === 0 ? 'Fizz' : i % 5 === 0 ? 'Buzz' : String(i))(i + 1)));
4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?