tips for this exercise?

Brian Quinlan brian at sweetapp.com
Tue Mar 28 15:30:03 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 = []
>      	number = random.choice(numbers)
>      	numbers.remove(number)
>      	fiveNumbers = fiveNumbers.append(number)
>      	return fiveNumbers
> 
> Other than being sort of ugly, this also has the side effect of actually 
> editing the original list, 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?

I would just write the function like this:

def genNumbers():
     shuffle_nums = numbers[:]    # copy the list to preserve the orginal
                                  # order (if it matters)
     random.shuffle(shuffle_nums) # shuffle the entire list
     return shuffle_nums[:5]      # return the first 5 elements

Cheers,
Brian





More information about the Python-list mailing list