Do you know FizzBuzz? I'm ashamed to say that the Lord didn't even know the word FizzBuzz until the other day, yeah.
So, I would like to summarize FizzBuzz after reviewing it.
Originally an English-speaking word game, it seems to be a game in which multiple players speak numbers in order from 1 according to the following conditions.
Example A「1」 B「2」 C「Fizz」 A「4」 B「Buzz」 ... A「13」 B「14」 C「FizzBuzz」
Well, it looks like this.
Now, let's simply implement it according to the rules without thinking about anything.
fizzbuzz.py
for num in range(1,101):
if num % 15 == 0:
print("FizzBuzz")
elif num % 3 == 0:
print("Fizz")
elif num % 5 == 0:
print("Buzz")
else:
print(num)
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Yes, it's done. It's very simple.
It would be convenient if we could change the number of divisions and the characters to be output.
fizzbuzz.py
div1, div2 = 4, 6
word1, word2 = "Nogi", "Zaka"
for num in range(1,101):
if num % div1 == 0:
if num % div2 == 0:
print(word1+word2)
else:
print(word1)
elif num % div2 == 0:
print(word2)
else:
print(num)
I recently learned about class, so I practice using class
python
class FizzBuzz:
def __init__(self, div, string):
self.div = div
self.string = string
def check(self,num):
if num % self.div == 0:
return self.string
else:
return ""
def main():
fizz = FizzBuzz(4, "Nogi")
buzz = FizzBuzz(6, "Zaka")
for num in range(1, 101):
result = fizz.check(num) + buzz.check(num)
if result == "":
print(num)
else:
print(result)
if __name__ == "__main__":
main()
1
2
3
Nogi
5
Zaka
7
Nogi
9
10
11
NogiZaka
13
14
15
Nogi
17
Zaka
19
Nogi
21
22
23
NogiZaka
It's done! Nogizaka hurray!
Recommended Posts