tips for this exercise?

Duncan Smith buzzard at urubu.freeserve.co.uk
Tue Mar 28 19:43:15 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?


Another approach (of possibly academic interest, if that).

>>> import random
>>> def genNumbers(k, n, draws):
     rand = random.randint
     numbers = range(1, n+1)
     for i in xrange(draws):
      for j in range(k):
       rand_int = rand(j, n-1)
       numbers[j], numbers[rand_int] = numbers[rand_int], numbers[j]
      yield numbers[:k]


>>> n = genNumbers(5, 54, 3)
>>> list(n)
[[23, 11, 9, 53, 45], [54, 29, 36, 22, 46], [20, 8, 29, 43, 12]]
>>>

Duncan



More information about the Python-list mailing list