在Python中的Fizz-Buzz程序
Fizz-Buzz是用于解释Fizz、Buzz和Fizz_Buzz组中的数字除法的编程任务。
假设用户有一个数字’n’,他们必须显示从1到n的所有数字的字符串表示。但是有一些限制,例如:
- 如果数字可以被3整除,则在数字的位置打印”Fizz”。
- 如果数字可以被5整除,则在结果中打印”Buzz”。
- 如果给定的数字既可以被3整除又可以被5整除,则在数字的位置打印”Fizz_Buzz”。
- 如果数字既不能被3整除又不能被5整除,则将数字作为字符串打印出来。
为了解决上述问题并考虑这些限制,我们必须按照以下步骤进行:
在程序中,我们必须对从1到’n’的所有数字应用这个条件。
示例:
class Example(object):
def Fizz_Buzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
for i in range(1 , n+1):
if i % 3 == 0 and i % 5 == 0:
result.append(" Fizz_Buzz ")
elif i % 3 == 0:
result.append(" Fizz ")
elif i % 5 == 0:
result.append(" Buzz ")
else:
result.append(str(i))
return Result
object1 = Example()
print(object1.Fizz_Buzz(55))
输出:
['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 ']
我们也可以使用循环方法来编写上面的程序。
示例:
for num in range(35):
# Numbers which are divisible by 15, that means it is divisible by both 3 and 5,
# it will print "Fizz_Buzz" # at the place of the number
if num % 15 == 0:
print(" Fizz_Buzz ")
continue
# Numbers which are dividable by 3, it will print "Fizz"
# at the place of the number
elif num % 3 == 0:
print(" Fizz")
continue
# Numbers which are dividable by 5,
# it will print "Buzz" at the
# place of the number
elif num % 5 == 0:
print(" Buzz ")
continue
# in result it will Print numbers
print(num)
输出:
Fizz_Buzz
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
总结
在本文中,我们讨论了用户如何为Fizz Buzz问题编写一个python程序,我们也讨论了一些必须遵循的限制。