Python Forum

Full Version: Can i prevent the random generator to generate already used numbers?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all!

I'm new to Python and played around a bit with the random module a little as a part of my learning process.
I wanted to do i lottery game that randomly spits out 7 numbers in the range of 1 to 34 and puts them in a list.

The problem is that the random generator will generate the same number more than once. I was able to solve this by generating a new set of numbers if doubles were found. But what i would prefer to do is preventing the random generator to generate already used numbers, as it would in a real lottery game. The used numbers should be excluded from the random generator so to speak. Is this possible to do?

Thanks a lot for your help!

                for x in range(0, 7):
                        lottorad[x] = random.randint(1, 34)
Look at random.sample()
If you don't want the outputs to repeat
, you can make a list and a if statement to check if there such output in the list. Here's the code:
outputs = []
for x in range(7):
        lottorad[x] = random.randint(1, 34)
        if lottorad[x] in outputs:
                lottorad[x] = random.randint(1, 34)
        else:
                outputs.append(lottorad[x])
Sorry, if the script doesn't work. I just keep entering 'lottorad[x]' like a name of a variable
Thanks a lot all for your help, random.sample did the trick.


My code went from this:
import random

lottorad = [0, 0, 0, 0, 0, 0, 0]
unik_rad = False



while unik_rad == False:
        for x in range(0, 7):
                lottorad[x] = random.randint(1, 34)
        # lottoraden är nu fylld med 7 nummer.



        # kontrollerar om samtliga nummer i lottoraden är unika
        for x in range(1, 35):
                lika = lottorad.count(x)
                if lika > 1: # minst två lika nummer har hittats
                        unik_rad = False
                        break
                else:
                        unik_rad = True


lottorad.sort()
print(lottorad)
to this:
import random

lottorad = []
lottorad = random.sample(range(1, 34), 7)
lottorad.sort()
print(lottorad)
Thanks again, problem solved Smile