Reputation: 1
This is what I have so far:
import random
for x in range(10):
tickets = [random.sample(range(0,59), 6)]
print (tickets)
But I need to make it so that all the numbers generated are different except for two numbers which are the same.
So that's my problem and would appreciate help before Friday! This is the question I was asked for reference: "My new year's resolution is to win the lottery. To do this I will buy 10 tickets each week. I shall choose 6 numbers at random for each ticket. The numbers range from 1 to 59. All the numbers can only be used once except for one which will need to be duplicated. Write a program in python to simulate this."
Upvotes: 0
Views: 75
Reputation: 123423
You can avoid repeated numbers by keeping track of those that have been used and disallowing them in later samples:
import random
def non_repeating_random_sample(population, k, seen):
while True:
sample = random.sample(population, k)
if not any(number in seen for number in sample):
seen.union(sample)
return sample
seen = set()
for _ in range(10):
tickets = [non_repeating_random_sample(range(0, 59), 6, seen)]
print(tickets)
When doing something like this, it may be important to understand that the samples returned—except for the first one—aren't really random because of the additional restraint.
Regardless, it would be simpler and faster to just shuffle the entire population, and then extract groups of of the desired size from it:
import random
number_of_samples = 10
number_per_sample = 6
samples = list(range(number_of_samples*number_per_sample))
random.shuffle(samples)
generator = zip(*[iter(samples)]*number_per_sample)
for _ in range(number_of_samples):
print(list(next(generator)))
Upvotes: 1