tags:

views:

62

answers:

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

+3  A: 

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

newacct
+3  A: 

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]
ABentSpoon
Ah, I keep making this (indentation) mistake! I think I need to move from Textmate to some real IDE while I'm just a beginner. Thanks!
Nimbuz
Nah, textmate should be fine; no ide would have helped you with that one. Maybe check out pdb though :).
ABentSpoon