tips for this exercise?

Steve M sjmaster at gmail.com
Tue Mar 28 15:44:44 EST 2006


You have two lines inside the loop that ought to be outside the loop -
the initial assignment to fiveNumbers and the return statement. Also,
the line that appends new numbers to fiveNumbers is not quite correct -
the append() method modifies the list in place, rather than return a
new list.

Here's one that does what you seem to want. It exploits the fact that a
given number can't be in a set twice. It eliminates having to modify
and recreate the numbers list, but incurs the risk of calling choice()
more than five times; however each such extra call to choice is
increasingly improbable...

from random import choice
numbers = range(1,54)

def genNumbers():
    fiveNumbers = set()
    while len(fiveNumbers) < 5:
        fiveNumbers.add(choice(numbers))
    return list(fiveNumbers)




More information about the Python-list mailing list