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

PythonでFizzBuzz

Posted at

PythonでFizzBuzz

FizzBuzzとは?

数字が3で割り切れると Fizz
数字が5で割り切れると Buzz
数字が3でも5でも割り切れると FizzBuzz
上記以外の場合は、そのまま数値を出す
(本来は、海外の言葉遊びらしいです。wiki参照

PythonでFizzBuzzやってみる。

普通にやると

python
def FizzBuzz(x):
    if x % 3 == 0 and x % 5 == 0:
        return "FizzBuzz"
    if x % 3 == 0:
        return "Fizz"
    if x % 5 == 0:
        return "Buzz"
    return x

こんな感じでしょうか

ちょっと変わった感じに書いてみる

python3
def fizbuz(num):
    try:
        dic = {(True, True): "FizzBuzz", (True, False): "Fizz", (False, True): "Buzz"}
        return dic[num%3==0, num%5==0]
    except:
        return num

いかがでしょうか?

後者ではif文がありません。

いろんなアプローチがあると思うので、是非皆さんも考えてみてください:point_up:

1
1
2

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
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?