[Tutor] Python Programming for the absolute beginner 3e, Ch3 Challenge 4

ALAN GAULD alan.gauld at btinternet.com
Sat Aug 10 13:04:57 CEST 2013


Also don't know how to do a binary chop, but the book hasn't covered anything 
>like that - it has just taught if, else and while, 
>
>A binary chop is an algorithm. All you need is if/else and while.
The algorithm looks a bit like this:

while not found
       determine the middle value between min  and max
       if value > target set max to value
       if value < target set min to value
       else found = True

the_number = int(input("Type in a number - I swear down I no look!^^ "))You don't need to store the number since the human user can just remember it

print("But I asked the computer, and it reckons your number is...")
>
>guess = (random.randint(1, 100))You don't want to use random guesses - that could take a very long time!

while guess != the_number:
>
>    hilo = input("\nWas I too high or too low?  Write 'h' or 'l'.\n")
>    if hilo == "h":
>        print("\nToo high, well, in that case what about...\n")
>        lower_guess = (random.randint(lowest, temp))This is almost right except you will be faster using the mid value rather than a random one.

And what happened in the shell:
>
>
>
>Hello & Welcome to 'Modified Guess My Number'!
>
>
>Think of a number between 1 and 100 & the computer has to guess it.
>Type in a number - I swear down I no look!^^ 30
>OK you wrote 30 but I no show the computer.
>
>
>But I asked the computer, and it reckons your number is...
>57
>
>
>Was I too high or too low?  Write 'h' or 'l'.
>h
>
>
>Too high, well, in that case what about...
>
>
>10
>
>
>Was I too high or too low?  Write 'h' or 'l'.
>l
>
>
>Too low, well, in that case what about...
>
>
>53
>
>
>Was I too high or too low?  Write 'h' or 'l'.
>h
>
>
>Too high, well, in that case what about...
>
>
>51
>
>
>Was I too high or too low?  Write 'h' or 'l'.
>hAs you can see its working, but just taking a lot of guesses. 
You will speed it up dramatically if you calculate the mid 
point rather than use random.

HTH

Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130810/862557b1/attachment.html>


More information about the Tutor mailing list