I have a function here that returns a 4 digit string. The problem is that when I run the function like 500 times or more, it starts to return duplicates. How to avoid that?
My Function:
import random
def CreatePass():
Num = str(random.randint(1000, 9999)
return Num
A random sequence without duplicates isn't random.
You can reduce the likelihood of duplicates by increasing the range of possible values.
Alternatively, you can record previous return values, and choose a new value if it has been previously returned.
Finally, you could generate the whole sequence, then shuffle it.
Of course, you then need to figure out what to do once you have exhausted the possible return values, as well as the whether the behaviour once there are only a small number of possible return values is actually desirable.
Also, you should comply with standard Python coding standards.
Generate a list, shuffle that and pop from it each time the function is called:
Note that this re-generates the
_numbers
list once you've run out, but then you've used up all 8999 possible numbers and would have to accept repetitions anyway.Could just roll your own, and hope not to exhaust it:
You'll get a
StopIteration
when it's exhausted though...@Martijn's solution is enough since you only need to store and shuffle 9000 numbers. If you want numbers from a bigger range and you know (approximately) how many numbers you'll need, there's a better way: The function
random.sample
will give you numbers in the desired rangewithout
repetition. For example, to get 500 distinct six-digit numbers you'd use: