Hi, I´m in lesson Nº 4, with the farmyard problem. I don´t know how does the def solve() function actually works, I mean, I´ve tried to do the table that the professor did (0+1+2+3+4 etc) to check it how it gets to the result, but do not understand how. Has anyone manage to understand this properly? Thanks!!!
Here´s how it looks like: 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=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 print "Number of Chickens:", chickens Now, the professor does: barnYard() and it replies: Enter the number of heads He types 20 And after that it asks Enter the number of legs and he types 56 It replies Number of pigs: 8 Number of Chickens: 12
It's like that: the solution uses a for loop, that works looping over some j element, for bottom_limit <= j <= up_limit. Now, when it enters the loop, j acquires some value (0, 1, etc). In terms of the barn yard problem, the solve function will firstly change the test-value for numPigs (you understand why it's numHeads - numChicks? It's the total head count, and every animal has only one head), the it checks if totLegs (4*number_of_pigs + 2*number_of_chickens) is equal to numLegs. If it is for some value j in the loop, then the function returns the solution(numPigs,numChicks). Else, (if it loops the whole loop without returning anything) then it returns (None,None). Hope this was helpful.
Thanks bmp! I think I got this somewhat clearer now, I didn´t quite get the return (None,None)... When you say "j", you mean numblegs or numbeads, right? I mean when you say j you mean the user´s input, rigth? Thanks for your reply!!!
Yup, in this case is the numChicks initialized in the for loop (for numChicks in ..). The return (None,None) acts just like a sentinel, so to speak, so you proceed accordingly if you aren't working directly with the function. That is, it allows you to know whether or not a given input has a solution in the barnYard() function, just checking whether or not the return is equal to None. It allows more control to the probable outputs in runtime.
Join our real-time social learning platform and learn together with your friends!