python中FizzBuzz测试的正确输出是什么?
我最近开始学习python,并尝试了FizzBuzz测试。我想到了这个:python中FizzBuzz测试的正确输出是什么?,python,fizzbuzz,Python,Fizzbuzz,我最近开始学习python,并尝试了FizzBuzz测试。我想到了这个: count = 0 while count <= 100: if (count % 3) == 0: print "Fizz" count = count + 1 elif (count % 5) == 0: print "Buzz" count = count + 1 elif (count % 5) and (count % 3)
count = 0
while count <= 100:
if (count % 3) == 0:
print "Fizz"
count = count + 1
elif (count % 5) == 0:
print "Buzz"
count = count + 1
elif (count % 5) and (count % 3):
print "FizzBuzz"
count = count + 1
else:
print count
count = count + 1
这不是正确的输出。如何清理程序?想想这些语句的出现顺序
elif (count % 5) and (count % 3):
这行代码永远不会执行,因为
if (count % 3) == 0:
或
如果这些条件为真,将首先执行。在这个
如果您想检查这些条件是否均为真,
只有到那时,您才应该检查单个条件是否为真
还有,代码行
count = count + 1
出现在代码的每一个分支中,考虑把它放在某个地方。
每一次都会执行一次
但是我会选择使用for循环而不是while循环
for x in range(100):
这样就不需要额外的计数变量
还有一件事需要注意
elif (count % 5) and (count % 3):
在这里,您不是在检查数字%5是否为==0,而是在检查(计数%5)。因此,表达式“if(count%5)”将在count不是可被5整除的情况下生成True(检查真值测试)。对于省略==比较器的其他地方也是如此
这里有一个与您类似的方法的示例
for count in range(1, 101):
if count % 5 == 0 and count % 3 == 0:
print "FizzBuzz"
elif count % 5 == 0:
print "Buzz"
elif count % 3 == 0 and count % 5 == 0:
print "Fizz"
else:
print count
注意事项:
- 在检查个别情况之前,先检查两种情况
- for循环而不是while循环(个人偏好)
- 正在检查==0
- 一个数字可以被3和5整除
- 一个数字可以被3整除,但不能被5整除
- 一个数字可以被5整除,但不能被3整除
- 数字既不能被5整除,也不能被3整除 声明变量。我添加了额外的变量,只是为了确保事情进展顺利。如果愿意,您可以跳过后跟“可除的_by”的变量
- 我认为逻辑是检查
myArray = []
divisible_by_both = []
divisible_by_three = []
divisible_by_five = []
digits = range(1,101)
编写循环和条件
for x in digits:
if (x % 3 == 0) and (x % 5 == 0):
myArray.append("Fizzbuzz")
divisible_by_both.append(x)
if (x % 3 == 0) and not (x % 5 == 0):
divisible_by_three.append(x)
myArray.append("Fizz")
if not (x % 3 == 0) and (x % 5 == 0):
divisible_by_five.append(x)
myArray.append("Buzz")
if not (x % 3 == 0) and not (x % 5 == 0):
myArray.append(x)
打印结果,或打印其他数组以确保总长度为100
print(myArray)
这是输出。如果愿意,可以加入数组并将其作为字符串输出。
[1,2,'Fizz',4,'Buzz',Fizz',7,8,'Fizz',Buzz',11,'Fizz',13,14,'Fizz',16,17,'Fizz',19,'Buzz',Buzz',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 26,'Fizz 52,53,'Buzz 56,'Fizz 58'9、‘嘶嘶’、61、62、‘嘶嘶’、64、‘嘶嘶’、67、68、‘嘶嘶’、‘嘶嘶’、71、‘嘶嘶’、73、74、‘嘶嘶’、76、77、‘嘶嘶’、79、‘嘶嘶’、‘嘶嘶’、82、83、‘嘶嘶’、‘嘶嘶’、86、‘嘶嘶嘶’、88、89、‘嘶嘶嘶’、91、92、‘嘶嘶’、‘嘶嘶’、‘嘶’、‘嘶嘶’、‘嘶’、‘嘶嘶’、‘嘶’、‘嘶’、‘嘶’、‘嘶’、‘嘶’、‘嘶’、。对于代码中出现的数字来说,这永远是正确的。问题,而不是故事。你可能想看看如何做。为了澄清@MorganThrapp所说的,所有正整数和负整数都是正确的。只有0是假的。你在做一个逻辑测试“真与真”来检查3和5。我真的希望有人把它作为家庭作业解决方案或面试解决方案:P
for x in digits:
if (x % 3 == 0) and (x % 5 == 0):
myArray.append("Fizzbuzz")
divisible_by_both.append(x)
if (x % 3 == 0) and not (x % 5 == 0):
divisible_by_three.append(x)
myArray.append("Fizz")
if not (x % 3 == 0) and (x % 5 == 0):
divisible_by_five.append(x)
myArray.append("Buzz")
if not (x % 3 == 0) and not (x % 5 == 0):
myArray.append(x)
print(myArray)