0

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)
Amit
  • 5
  • 1
  • 2
  • 6

2 Answers2

2

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)
jfbeltran
  • 1,808
  • 3
  • 13
  • 17
1

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]
Tony
  • 9,672
  • 3
  • 47
  • 75
  • 2
    Or as a dictionary with the number as the key and None as the value. Then, if you want to look up a newly generated number, all you have to do is see if: new_number in dict – Ben Sep 22 '17 at 18:34
  • 1
    @Ben: That's a set. – quamrana Sep 22 '17 at 20:01
  • @quamrana Great point! I am so used to working with dicts that I completely forgot about sets. Sets are the better way here. – Ben Sep 22 '17 at 21:23