Fix A Function Returning Duplicates Over Time?
Solution 1:
Generate a list, shuffle that and pop from it each time the function is called:
import random
defCreatePass(_numbers=[]):
ifnot _numbers:
_numbers[:] = range(1000, 10000)
random.shuffle(_numbers)
returnstr(_numbers.pop())
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.
Solution 2:
@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 range without
repetition. For example, to get 500 distinct six-digit numbers you'd use:
selected = random.sample(xrange(100000, 1000000), 500)
Solution 3:
Could just roll your own, and hope not to exhaust it:
from random import shuffle
defmyrandom(start, end):
possible = range(start, end)
shuffle(possible)
for i in possible:
yieldstr(i)
randoms = myrand(1000, 9999)
printnext(randoms)
printnext(randoms)
# etc...
You'll get a StopIteration
when it's exhausted though...
Solution 4:
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.
Post a Comment for "Fix A Function Returning Duplicates Over Time?"