# Barn yard example: counting heads and legs
def solve(numLegs, numHeads):
for numChicks in range(0, numHeads + 1):
numPigs = numHeads - numChicks
totLegs = 4*numPigs + 2*numChicks
if totLegs == numLegs:
return [numPigs, numChicks]
return [None, None]
def barnYard(heads, legs):
pigs, chickens = solve(legs, heads)
if pigs == None:
print "There is no solution."
else:
print 'Number of pigs: ', pigs
print 'Number of Chickens: ', chickens
barnYard(20,56)
我认为预期的结果是8和12,但它返回'没有解决方案'。我做错了什么?
我刚开始编程,所以请你好......:)
答案 0 :(得分:3)
看看你的缩进。 return [None, None]
在循环中。它在第一次迭代后返回[None, None]
答案 1 :(得分:3)
在solve()
中,您的return语句缩进为for循环内部。支持一个级别,它应该可以正常工作。
def solve(numLegs, numHeads):
for numChicks in range(0, numHeads + 1):
numPigs = numHeads - numChicks
totLegs = 4*numPigs + 2*numChicks
if totLegs == numLegs:
return [numPigs, numChicks]
return [None, None]