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
I’m learning Python and came across this example, can someone please explain in plain english (or pseudo-code) what this is doing line by line.
Many thanks
solveis computing how many chicks (1 head, 2 legs) and how many pigs (1 head, 4 legs) it takes to total up to the given numbers of heads and legs.It uses a “brute force”, that is, maximally simple, approach:
chicks from none at all to as many as
was specified as number of heads
(that’s the role of the loop
for, sincenumChicks in range(0, numHeads +
1):
rangegives integersfrom the starting value included
to the ending value excluded);
numChicksit computeshow many pigs there would be to give
the requested number of heads, by the
statement
numPigs = numHeads - numChicksthose chicks and pigs would have, by
totLegs = 4*numPigs + 2*numChickstotLegsequalthe requested number: if so, it returns
a list with two items, the numbers of
chicks and pigs that solve the problem
the
forloop without having returneda value yet, it knows there’s no solution,
and signifies that by returning a list
each of whose two items is
None.barnYardjust delegates the solution tosolve, and prints it out in a nice readable way, either as “no solution” or as nicely decorated numbers of chicks and pigs.Now, to keep progressing, ask yourself if
solvecould be written more efficiently. Clearly there is no solution if the number of legs is less than twice the number of heads, or more than four times the number of heads, or odd — maybesolvecould test for those case and return[None, None]immediately. Could you code that…?It may not be obvious, but every other combination of numbers of heads and legs has a solution — and there IS a way to find it just by arithmetic, without looping. Think about it, maybe with the help of elementary middle-school algebra…