eozzy
eozzy

Reputation: 68680

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 ... :)

Upvotes: 0

Views: 134

Answers (2)

ABentSpoon
ABentSpoon

Reputation: 5169

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]

Upvotes: 3

newacct
newacct

Reputation: 122449

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

Upvotes: 3

Related Questions