[Tutor] quick ?

Bob Gailer bgailer at alum.rpi.edu
Wed Sep 13 17:18:57 CEST 2006


dpotter at nc.rr.com wrote:
> I am new to Python (and programming).  In teaching myself I wrote a
> small program that will pick random lottery numbers, I want to check for
> duplicates and rerun the random function.  But I am hitting a wall. 
> This is what I think should work, but I still get duplicates.  TIA.
random.shuffle() is the predefined way to do this. But for more general 
things like this it is better to use a list to hold multiple values.

Example:

import random
picks = [] # collect unique picks
count = input("How many quick picks do you need? ")
while len(picks) < count:
  pick = random.randint(1,55)
  if not pick in picks: 
    picks.append(pick)
print picks

OR

import random
picks = [0]*55
count = input("How many quick picks do you need? ")
got = 0
while got < count:
  pick = random.randint(1,55)
  if not picks[pick]: 
    picks[pick] = 1
    got += 1
for i in range(len(picks)+1):
  if picks[i]:
    print i, 


-- 
Bob Gailer
510-978-4454



More information about the Tutor mailing list