I have few lines of code that generate random numbers,How can I stop generating duplicate numbers?
import random
num = random.randrange(0,1000)
x = 13
while num != x :
num = random.randrange(0 , 14)
print(num)
I have few lines of code that generate random numbers,How can I stop generating duplicate numbers?
import random
num = random.randrange(0,1000)
x = 13
while num != x :
num = random.randrange(0 , 14)
print(num)
If you can only pick each number once, this becomes the same as randomly sorting a list and picking one number at a time
import random
desired_number = 13
guesses = range(0,14)
random.shuffle(guesses)
current_guess = None
while current_guess != desired_number:
current_guess = guesses.pop()
print(current_guess)
Store the numbers as they are generated and check against this list for each new number.
Performance won't be great as the list to check gets longer, but at least you won't have duplicates.
Another way would be to generate a list of number from 1..n, shuffle the numbers and then iterate the list to get your next unique random number.
>>> import random
>>> l = list(range(4))
>>> random.shuffle(l)
>>> l
[3, 2, 4, 1]