Can i prevent the random generator to generate already used numbers? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Can i prevent the random generator to generate already used numbers? (/thread-23554.html) |
Can i prevent the random generator to generate already used numbers? - MauserMan - Jan-05-2020 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) RE: Can i prevent the random generator to generate already used numbers? - ichabod801 - Jan-05-2020 Look at random.sample() RE: Can i prevent the random generator to generate already used numbers? - _ShevaKadu - Jan-05-2020 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 RE: Can i prevent the random generator to generate already used numbers? - MauserMan - Jan-05-2020 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 |