I personally tackled the problem of Fizz Buzz! At Python-only Mokumokukai, so here is the result report!
With numbers from 1 to 398 If it is divisible by 3, "Fizz!" Is displayed. If it is divisible by 5, "Buzz!" Is displayed. If it is divisible by 3 and 5, "Fizz Buzz!" Will be displayed. In cases other than the above, the numbers are displayed as they are. Tip: Combine for and if statements
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)
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
I happened to get a theme, so I did it, but I think the problem with the URL below is the cause. https://qiita.com/Sekky0905/items/7e2b13f2a001384c7fc4
Recommended Posts