Skip navigation.

Maudlin ruminations of a mind bit by wanderlust.

And a shaft of light shall sunder the heavens...

Playing the 'Guess my number' game recursively

,

This has probably occurred to a lot of you, but I only just realized it, after reading a book on Haskell. I'd never thought of it before.

Most programmers have written their own version of the 'Guess my number' game -- You know, it picks a number, you guess, it says if you're too high or too low, that kind of thing.

What we usually do is this :

def guess(n) :
    while True :
        x = int(raw_input('Enter a number : '))
        if x < n :
            print 'You're too low.'
        if x > n :
            print 'You're too high.'
        if x == n :
            print 'You're absolutely right.'
            return


I'd never realized that it could be done recursively, although it looks pretty obvious. No, it doesn't offer any performance boosts, and no, it doesn't make it easier to read. It's just something different.

def guess(n) :
    x = int(raw_input('Enter a number : '))
    if x < n :
        print 'You're too low.'
        guess(n)
        return
    if x > n :
        print 'You're too high.'
        guess(n)
        return
    if x == n :
        print 'You're absolutely right.'
        return


The usefulness of recursion is not perhaps as apparrent in this case as it usually is, but still...

Java, anyone?The Towers of Hanoi, recursion, and the end of the world.

Comments

Mick-E 14. June 2007, 16:37

Thanks for the code samples :up:

Anonymous 1. September 2008, 02:39

- writes:

swerewd

How to use Quote function:

  1. Select some text
  2. Click on the Quote link

Write a comment

Comment
(BBcode and HTML is turned off for anonymous user comments.)

If you can't read the words, press the small reload icon.


Smilies

Download Opera, the fastest and most secure browser
December 2009
S M T W T F S
November 2009January 2010
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