python - How to generate random numbers that are different? -


possible duplicate:
pick n items @ random

i need generate 6 random numbers between 1 , 49, cannot same. know how make them random, not sure how ensure different.

the worksheet recommends displaying each number , setting zero, don't see how help.

any advice appreciated.

you can use random.sample:

>>> random.sample(xrange(1,50), 6) [26, 39, 36, 46, 37, 1] 

"the worksheet recommends displaying each number , setting zero, don't see how help."

assuming assignment , need implement sampling yourself, take @ how random.sample implemented. it's informative, may complicated needs since code ensures sub-slices valid random sample. efficiency, uses different approaches depending on population size.

as worksheet, believe assumes you're starting off list of numbers 1 49 , suggests replace numbers you're selected 0 there can skipped if reselected. here's pseudo code started:

 population = range(1, 50)  # list of numbers 1 49 sample = [] until 6 samples:   index = random number 0 48  # random.randint()   if population[index] not 0:  # if found unmarked value     append population[index] sample     set population[index] = 0  # mark selected 

if wish attempt different, there many other approaches consider e.g. randomising list truncating, or form of reservoir sampling.

good luck assignment.


Comments