函数获取python中的动物数

2024-03-28 13:58:16 发布

您现在位置:Python中文网/ 问答频道 /正文

Hello这些函数根据这两个动物的头和腿的输入返回猪和鸡的数量。我对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()函数。我们将感谢您的帮助。


Tags: of函数nonenumber数量defheadssolve
1条回答
网友
1楼 · 发布于 2024-03-28 13:58:16

基本上:

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

所以:

基本上,它会一遍又一遍地运行函数,直到计算出的腿数等于输入的腿总数。如果它永远不等于,它只会返回[无,无]。(return[numPigs,numChicks]中断for循环)

编辑: 我试着把2号线的+1去掉,结果还是很好。

相关问题 更多 >