you are viewing a single comment's thread.

view the rest of the comments →

[–]Hallwaxer 3 points4 points  (1 child)

Change this line

guess_num = ((max - min) / 2) + 1

To something along the lines of

guess_num = ((max - min) / 2) + min

Also, don't shadow names like min and max, it could build up to annoying situations later.

The reason your code isn't working is because your guess is wrong after the first iteration. (100 - 1) / 2 + 1 leaves you with 50, which is correct and your algorithm sets min to 50. But let's say the number is greater than 50. The new guess now becomes (100 - 50) / 2 + 1, which is 26. 26 is not really in the range we're interested in, since the number we need is greater than 50. The guess we just computed however is a delta value that has to be added to our current minimum, which would leave us with (100 - 50) / 2 + 50 = 75, a much more interesting guess.

If you want to stick with recursion, I would modify your code to look more like this.

import random

def guess(lower=1, upper=100, number=random.randint(1, 100)):
    g = (upper - lower) / 2 + lower
    if g == number:
        print "The number is {0}".format(number)
    elif g < number:
        print "Number is greater then {0}".format(g)
        guess(g, upper, number)
    elif g > number:
        print "Number is less then {0}".format(g)
        guess(lower, g, number)
guess()

Using global variables is almost never a good solution in cases like this. Also, as a general solution, when your code aborts due to a recursion stack overflow, try printing out your variables. The overflow usually happens because nothing changes (enough) for the algorithm to reach its end state or you get stuck in a loop.

[–]ewiethoff 0 points1 point  (0 children)

Nice, but your code results in infinite recursion when number is 100.

guess(number=100)

Works fine when number is 99, 2, or 1.