tips for this exercise?

bruno at modulix onurb at xiludom.gro
Wed Mar 29 04:07:36 EST 2006


John Salerno wrote:
> I'm working on another exercise now about generating random numbers for
> the lottery. What I want to do is write a function that picks 5 random
> numbers from 1-53 and returns them. Here's what I have so far:
> 
> numbers = range(1, 54)
>
> def genNumbers():
>     for x in range(5):
>         fiveNumbers = []

You rebind fiveNumbers on each iteration - so the results of the
previous iteration are lost.

>         number = random.choice(numbers)
>         numbers.remove(number)

ok, you already know the problem with this line

>         fiveNumbers = fiveNumbers.append(number)

list.append() returns None. Guess what will be the value of fiveNumbers
after this statement ?

>         return fiveNumbers

And you exit the function at the first iteration.

> Other than being sort of ugly, this also has the side effect of actually
> editing the original list,

This is not the only problem here !-)

> which I don't want since I will want to
> generate more than one set of numbers.
> 
> Is there a better way to extract a certain number of items from a list
> (so maybe I don't need the for loop)? Is a list even the right type to
> use, since it gets edited in place? Perhaps a set?

Your code is wrong, but still close to the simplest solution. Using
random.choice() and removing used items from the list to choose from
seems quite ok to me. Now shat you need to do is:
1/ create a new list to choose from each time the function is called
2/ create the results list *before* the loop
3/ return *after* the loop

The simplest fix:

def genNumbers():
    choose_from = range(1, 54)
    results = []
    for x in range(5):
        number = random.choice(choose_from)
        choose_from.remove(number)
        results.append(number)
    # end for
    return results

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list