Implement the basic algorithm in Python to deepen your understanding of the algorithm. The first of these is the FizzBuzz problem.
While displaying a series of numbers in order, "Fizz" is displayed if it is a multiple of 3, "Buzz" is displayed if it is a multiple of 5, and "FizzBuzz" is displayed instead of a number if it is a multiple of both 3 and 5. That is. It seems easy, but I will actually implement it once to see the details. This time, we will deal with 1 to 100 FizzBuzz problems.
FizzBuzz
"""
2020/12/15
@Yuya Shimizu
FizzBuzz
1~Numbers up to 100 are displayed in order, and those divisible by 3 are Fizz,
Those that are divisible by 5 are displayed as Buzz, and those that are divisible by 3 or 5 are displayed as FizzBuzz.
"""
# FizzBuzz
for i in range(1, 101):
#Generally, it is easier to see if you write from a special case
if (i%3==0) and (i%5==0):
print('FizzBuzz', end=' ') #end as an argument to print= ' 'If so, it will be displayed with a space without line breaks.
elif i%3==0:
print('Fizz', end=' ')
elif i%5==0:
print('Buzz', end=' ')
else:
print(i, end=' ')
As described in the comment of the implementation code, if end ='' is set as an argument of print, it will be displayed with a space without line breaks.
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz
Certainly, it can be seen that "Fizz" is displayed for multiples of 3, "Buzz" is displayed for multiples of 5, and "FizzBuzz" is displayed for multiples of both 3 and 5.
I didn't know that it is possible to display with spaces without automatic line breaks when multiple prints are used by simply setting end ='' to the argument of print that has been used frequently. It was good to know. It was also reconfirmed that the conditions must be set with priority given to special cases.
Introduction to algorithms starting with Python: Standards and computational complexity learned with traditional algorithms Written by Toshikatsu Masui, Shoeisha
Recommended Posts