0
1

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 で Fizz Buzz! の問題に5パターン挑戦(今だけ398までの数字)

Last updated at Posted at 2020-03-31

Python限定のもくもく会で、個人的にFizz Buzz! の問題に取り組んだので、そこでの成果報告です!

Fizz Buzz の問題にチャレンジ

1~398までの数字で、
3で割り切れれば、「Fizz!」を表示する
5で割り切れれば、「Buzz!」を表示する
3と5で割り切れれば、「Fizz Buzz!」を表示する
上記以外の場合は、そのままの数字を表示する
ヒント:for 文と if 文を組み合わせる

シンプルにforとifしか使わない例

sample1.py
for x in range(398):
    x = x + 1
    if x % 3 == 0:
        if x % 5 == 0:
            fb = "Fizz Buzz!"
        if x % 5 != 0:
            fb = "Fizz!"
    if x % 3 != 0:
        if x % 5 == 0:
            fb = "Buzz!"
        if x % 5 != 0:
            fb = x
    print(fb)

andとかorとかelifとかいうものを使う例

sample2.py
for x in range(398):
    x = x + 1
    if x % 3 == 0 and x % 5 == 0:
        fb = "Fizz Buzz!"
    elif x % 3 == 0:
        fb = "Fizz!"
    elif x % 5 == 0:
        fb = "Buzz!"
    else:
        fb = x
    print(fb)

関数を使う例

sample3.py
def fb(x):
    if x % 3 == 0 and x % 5 == 0:
        fb = "Fizz Buzz!"
    elif x % 3 == 0:
        fb = "Fizz!"
    elif x % 5 == 0:
        fb = "Buzz!"
    else:
        fb = x
    print(fb)

for x in range(398):
    x = x + 1
    fb(x)

再帰呼出しを使った例

sample4.py
def count(x):
    if x > 1:
        count(x - 1)
    fb(x)

def fb(x):
    if x % 15 == 0:
        fb = "Fizz Buzz!"
    elif x % 3 == 0:
        fb = "Fizz!"
    elif x % 5 == 0:
        fb = "Buzz!"
    else:
        fb = x
    print(fb)
        
count(398)

クラスを使う例

sample5.py
class FizzBuzz:
    def __init__(self, x):
        self.count(x)

    def count(self, x):
        if x > 1:
            self.count(x - 1)
        self.fb(x)

    def fb(self, x):
        if x % 15 == 0:
            fb = "Fizz Buzz!"
        elif x % 3 == 0:
            fb = "Fizz!"
        elif x % 5 == 0:
            fb = "Buzz!"
        else:
            fb = x
        print(fb)

FizzBuzz(398)

出力結果

1
2
Fizz!
4
Buzz!
Fizz!
7
8
Fizz!
Buzz!
11
Fizz!
13
14
Fizz Buzz!
16
17
Fizz!
19
Buzz!
Fizz!
22
23
Fizz!
Buzz!
26
Fizz!
28
29
Fizz Buzz!
31
32
Fizz!
34
Buzz!
Fizz!
37
38
Fizz!
Buzz!
41
Fizz!
43
44
Fizz Buzz!
46
47
Fizz!
49
Buzz!
Fizz!

...
...
...

386
Fizz!
388
389
Fizz Buzz!
391
392
Fizz!
394
Buzz!
Fizz!
397
398

問題出典元

たまたまお題が出されたのでやったのですが、下記のURLの問題が大元かと思います。
https://qiita.com/Sekky0905/items/7e2b13f2a001384c7fc4

0
1
8

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?