函数获取python中的动物数量

时间:2015-03-28 05:45:58

标签: python function python-2.7

你好这些函数根据这两只动物头部和腿部的输入返回猪和鸡的数量。我是python的新手。我无法理解它是如何工作的。你能详细解释一下吗?

def solve(numLegs, numHeads):
    for numChick 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 = 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

因此,当我运行barnYard功能时,它会询问头数,所以我放了20个头,然后放了56个腿。它打印了8只猪和数鸡12只。但我真的无法理解它在这个阶段是如何达到的。特别是solve()函数。帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

基本上:

def solve(numLegs, numHeads):
    for numChick in range(0, numHeads + 1): #for every number in the range 0 - the number of heads + 1, numChick = that number
        numPigs = numHeads - numChicks #the number of Pigs equals the number of heads entered minus the current number
        totLegs = 4 * numPigs + 2* numChicks #the amount of legs is 4(amount of legs) * number of heads + 2(chicken legs) * the current number
        if totLegs == numLegs: if the pigs legs + the chicken legs = the total number of legs, 
           return [numPigs, numChicks] #return the number of pigs and chickens
    return[None, None] #else, return none, triggering "no solution"

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

所以:

基本上,它将反复运行该功能,直到计算的腿数等于输入的腿总数。如果它永远不等于,它只返回[none,none]。 (return [numPigs,numChicks]打破for循环)

修改 我尝试在第2行取出+1,但它仍然可以正常工作。