Welcome, guest | Sign In | My Account | Store | Cart

most number guessing programs make you guess the number but heres one where the computer guesses ether random or the most efficient way.

Python, 56 lines
 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64``` ```##################################################################### # program name: guess.py # auther: max baseman # email: dos.fool@gmail.com # date: 5/01/07 # short description: # this is a program that has two features # one that randomly picks numbers till it gets yours # and one that picks the most effective way till it gets your number ##################################################################### from random import randrange as random print "welcome to a number guessing program" print print "enter 1 for random " print "or" print "enter 2 for efficient" print guesstype=input(" >") if guesstype == 1: number=input("pick a number >") numrange=input("pick a range >")+1 guessed= guess=random(numrange) if guess==0: guess=random(numrange) print guess guessed.append(guess) guesses=1 while guess!=number: guessed.append(guess) guesses=guesses+1 guess=random(numrange) if guess in guessed: while guess in guessed: guess=random(numrange) print guess print"i got the number",number,"in",guesses,"guesses, out of a range of",numrange-1 elif guesstype == 2: number=input("pick a number >") numrange=input("pick a range >")+1 guess=numrange/2 print guess guesses=1 min=0 max=numrange while guess!=number: if guess < number: min=guess else: max=guess guess = (min+max) /2 guesses= guesses +1 print guess print "i got the number",number,"in",guesses,"guesses, out of a range of",numrange-1 print ```

this program is mostly for fun maybe if someone was working in number theory or pasterns in randomness this might be useful.

#### 1 comment Steven Bethard 16 years, 2 months ago

A cleaner, more extensible version.

``````import random
import textwrap

def iter_random_guesses(n, max):
guessed = set()
while True:
guess = random.randrange(max)
if guess in guessed:
continue
else:
yield guess

def iter_efficient_guesses(n, max):
min = 0
while True:
guess = (min + max) / 2
yield guess
if guess &lt; n:
min = guess
else:
max = guess

if __name__ == '__main__':

guess_iter_map = {1: iter_random_guesses,
2: iter_efficient_guesses}

print textwrap.dedent('''\
welcome to a number guessing program

enter 1 for random
or
enter 2 for efficient
''')

guess_type = int(raw_input('> '))
n = int(raw_input('pick a number> '))
max = int(raw_input('pick a range > '))
get_guess_iter = guess_iter_map[guess_type]
guess_iter = get_guess_iter(n, max + 1)
for i, guess in enumerate(guess_iter):
print guess
if guess == n:
break
tup = n, i + 1, max
print 'I got the number %i in %i guesses, out of a range of %i' % tup
`````` Created by max baseman on Fri, 30 Mar 2007 (PSF)