[Tutor] problem with simple script

Steven D'Aprano steve at pearwood.info
Wed Jul 28 16:17:46 CEST 2010


On Wed, 28 Jul 2010 09:51:40 pm Richard D. Moores wrote:
> I have a practical need for a script that will give me a random int
> in the closed interval [n, m]. Please see
> <http://tutoree7.pastebin.com/xeCjE7bV>.

What is the purpose of this function?

def get_random_int(n, m):
    return randint(n, m)

Why call "get_random_int" instead of randint? It does *exactly* the same 
thing, only slower because of the extra indirection.

If the only reason is because you don't like the name randint, then the 
simple solution is this:

get_random_int = randint

Now get_random_int is another name for the same function, without any 
indirection.


> This works fine when I enter both n and m as, for example, "23, 56",
> or even "56, 23". But often the closed interval is [1, m], so I'd
> like to not have to enter the 1 in those cases, and just enter, say,
> "37" to mean the interval [1, 37]. 

Keep the front end (user interface) separate from the back end. Here's 
the back end:

def get_random_int(n, m=None):
    if m is None:  # only one argument given
        n, m = 1, n
    return randint(n, m)

def str_to_bounds(s):
    L = s.split(',', 1)  # Split a maximum of once.
    return [int(x) for x in L]


And here's the front end:

def get_interval_bounds():
    print("Get a random integer in closed interval [n, m]")
    s = input("Enter n, m: ")
    return str_to_bounds(s)

def main():
    prompt = "Enter 'q' to quit; nothing to get another random int: "
    while True:
        args = get_interval_bounds()
        print(get_random_int(*args))
        ans = input(prompt)
        if ans == 'q':
            print("Bye.") 
            # Waiting 2 seconds is not annoying enough, 
            # waiting 2.2 seconds is too annoying.
            sleep(2.1)  # Just annoying enough!
            return

main()


Hope this helps!



-- 
Steven D'Aprano


More information about the Tutor mailing list