为了说明这一点,我们有两种动物,一种是猪,另一种是鸡。用户输入这两种动物的头和腿的数量。例如,如果我们运行这个程序,输入20头56条腿,我们得到12只鸡和8头猪。看看这里:
def solve(numLegs, numHeads):
for numChicks in range(0, numHeads + 1): # how we get 12 chickens here?
numPigs = numHeads - numChicks # numpigs = 20 - 12 = 8 ?
totLegs = 4 * numPigs + 2* numChicks # 4 * 8 + 2 * 12 ?
if totLegs == numLegs:
return [numPigs, numChicks]
return[None, None]
def barnYard():
heads = int(raw_input('Enter number of heads:'))
legs = int(raw_input('Enter number of legs:'))
pigs, chickens = solve(legs, heads)
if pigs = None:
print 'there is no solution'
else:
print 'number of pigs:' , pigs
pirnt 'number of chickes:', chickens
我们计算totLegs = 4 * numPigs + 2* numChicks
知道猪有4条腿,鸡有2条腿,然后验证这是否与输入的腿数匹配,对吗?但是现在的问题是for numChicks in range(0, numHeads + 1):
它如何找到鸡肉的数量是12?如果没有找到鸡的数量,如果我没有错的话,我们就不能继续下一行了。你能解释一下吗?这让我很困惑。代数版本可以在这里找到。link
Don't make your life more complicated than it already is
,只需使用print command to see the intermediate values
,它是simple algebra
。顺便说一句,您的代码中有many errors
,它doesn't even compile
(主要是typos
,比如{fixed code which works:
输出
^{pr2}$这是简单的数学。
You have 20 heads, 56 legs. every pigs has 4 legs, every chicken 2 legs
所以
也就是说
X = 20 - Y
然后
56 = 4*(20-Y)+2*Y => 56 = 80 -4Y+2Y => 2Y = 80 - 56 => 2Y = 24 => Y = 12 Chicken
然后
X + 12 = 20 => X = 8 Pigs
:天
希望有帮助!!在
相关问题 更多 >
编程相关推荐