![](/img/trans.png)
[英]Program to find the smallest number evenly divisible by all numbers from 1 to 20
[英]Checking to see if a number is evenly divisible by other numbers with recursion in Python
冒着受到反对的风险,我将在序言中说这是编程班的中期问题。 但是,我已经提交了代码并通过了问题。 我更改了函数的名称,以使某人无法立即进行搜索并找到正确的代码,因为这不是我的目的。 我实际上是想从我写的两篇文章中找出真正更正确的内容。
这个问题告诉我们,某个快餐店以6、9和20为一包出售一口大小的鸡肉。它希望我们创建一个函数来判断给定数量的一口大小的鸡肉是否可以通过购买不同的包装获得。 例如,可以购买15个,因为6 + 9为15,但是不能购买16个,因为没有任何组合的组合等于15。我提交的代码“正确”为:
def isDivisible(n):
"""
n is an int
Returns True if some integer combination of 6, 9 and 20 equals n
Otherwise returns False.
"""
a, b, c = 20, 9, 6
if n == 0:
return True
elif n < 0:
return False
elif isDivisible(n - a) or isDivisible(n - b) or isDivisible(n - c):
return True
else:
return False
但是,我想,如果初始数字为0,它将返回True。 初始数字0是否被认为是“使用6、9和/或20购买该数量”? 我无法查看评分者使用的测试用例,所以我不知道评分者是否将0选作测试用例并确定True是可接受的答案。 我也不能只输入新的代码,因为这是中期的。 我决定创建第二个代码来处理初始情况0,并假设0实际上为False:
def isDivisible(n):
"""
n is an int
Returns True if some integer combination of 6, 9 and 20 equals n
Otherwise returns False.
"""
a, b, c = 20, 9, 6
if n == 0:
return False
else:
def helperDivisible(n):
if n == 0:
return True
elif n < 0:
return False
elif helperDivisible(n - a) or helperDivisible(n - b) or helperDivisible(n - c):
return True
else:
return False
return helperDivisible(n)
如您所见,我的第二个功能必须使用“助手”功能才能工作。 但是,我的总体问题是,如果分频器已将0作为初始输入进行测试,那么您认为哪个函数会提供正确的答案?
我认为第一个功能是正确的。
我的回答是第二个功能更正确,因为从技术上讲,使用6、9和/或20的包装不能购买初始数字0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.