简体   繁体   中英

Unexpected result on a simple example

# 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)

Expected result is 8 and 12 I think, but it returns 'There is no solution'. What am I doing wrong?

I'm just starting with programming, so please be nice ... :)

look at your indentation. return [None, None] is inside the loop. it returns [None, None] after the first iteration

In solve() , your return statement is indented to be inside of the for loop. Back it out one level, and it should work just fine.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM