Guess My Number Game

Heiko Wundram heikowu at ceosg.de
Sat May 15 09:58:22 EDT 2004


Am Samstag, 15. Mai 2004 15:44 schrieb EAS:
> Anyways, I've found out how to make a "guess my number game" where the
> player guesses a number between 1 and 100, but I want to switch things
> around. I want to be able to put in my own number and have the computer
> guess it. I already know how to make it guess (by using randrange) but I'm
> having a hard time making it smarter. (Like guessing higher or lower based
> on what it's told it needs to do.) Here's the code I have right now:

On average, the shortest possible runtime (and also a deterministic runtime of 
O(log2(high-low))) will be achieved if you use interval walking.

Thus:

number = 64
low = 1
high = 100
while low <> high:
	med = (low+high)//2
	tries += 1
	if med == number:
		print "I guessed your number:", med
	elif med < number:
		if med == low:
			print "I guessed your number:", med+1
			low = med+1
		else:
			low = med
	else:
		high = med
print "I needed", tries, "tries."

HTH!

Heiko.




More information about the Python-list mailing list