ok, I'm not quite sure whether I can ask this question, but I don't understand the solution given for the 6th question in Quiz 2. Following is the algorithm I wrote for the cmpGuess function (in order to check my own solution):
""" Assumes that guess is an integer in range(maxVal).
Returns -1 if guess is < magic number, 0 if ==, 1 if > """
if guess < magicNumber: return -1
if guess > magicNumber: return 1
if guess == magicNumber: return 0
Is my understanding of the specification of the function right or wrong?
MIT 6.00 Intro Computer Science (OCW)
Stacey Warren - Expert brainly.com
Hey! We 've verified this expert answer for you, click below to unlock the details :)
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.
Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.
Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
I got my questions answered at brainly.com in under 10 minutes. Go to brainly.com now for free help!
It'll return those values, 1 for higher than 4, 0 equal to 4, -1 less than 4.
That is what I thought as well. The following is the coding given in the solution sheet for question 6 of Quiz 2. Integrating this coding with the above coding doesn't result in the expected solution to the problem. e.g.: if the statement "findNumber(50)" is given, the answer returned is 49, not 4, as it should be. Is the solution given in the marking scheme wrong? or is my coding wrong? Can you please explain this? Thanks
""" Assumes that maxVal is a positive integer.
Returns a number, num, such that
cmpGuess(num) == 0 """
s = range(0, maxVal)
return bsearch(s, 0, len(s) -1)
def bsearch(s, first, last):
if (last -first) < 2:
if cmpGuess(s[first]) == 0:
mid = first + (last -first)/2
if cmpGuess(s[mid]) == 0:
if cmpGuess(s[mid]) == -1:
return bsearch(s, first, mid -1)
return bsearch(s, mid + 1, last)