Reputation: 313
in the code below is it possible that it prints a number twice?
import random
n = 0
lista = (345, 348, 333, 347, 346, 340, 342, 349, 330, 331, 334, 335, 336, 337, 338, 339, 360, 366, 368, 320, 324, 327, 328, 329, 380, 388, 389, 391, 392, 393)
while n < 150:
x = random.randint(234325,876432)
x = str(x)
z = str(random.choice(lista)) + x
n += 1
print z
Upvotes: 0
Views: 226
Reputation: 3964
Yep.
Run it and compare the length of the list to the length of the list without duplicates. Only stop the loop if the numbers are different (there's a duplicate):
import random
listb = []
def random_numbers():
n = 0
lista = (345, 348, 333, 347, 346, 340, 342, 349, 330, 331, 334, 335, 336, 337, 338, 339, 360, 366, 368, 320, 324, 327, 328, 329, 380, 388, 389, 391, 392, 393)
while n < 150:
x = random.randint(234325,876432)
x = str(x)
z = str(random.choice(lista)) + x
n += 1
listb.append(z)
iterations = 0
while len(listb) == len(set(listb)):
listb = []
iterations += 1
random_numbers()
print len(listb), len(set(listb))
print iterations
Upvotes: 1
Reputation: 126
Is it possible? Absolutely.
The chances aren't great, but there is still a distinct possibility.
To give you an idea of the probability:
x has a range of 642,107
possible values.
lista has a range of 30
possible values.
So you have a total space of 30*642,107 = 19,263,210
possible combinations.
To get the probability, you have to understand the Birthday Paradox to give the chance of a collision.
p(x) = 1 - p'(x) = 1 - \prod\limits_{i = 0}^{149}(1 - \frac{i}{19,263,210})
= 1 - \frac{(19,263,210 permute 149)}{19,263,210^{149}}
= 0.00057
So you have about a 0.05%-0.06% chance of a collision every time this runs.
On average, after about 2,000 executions you will have a collision at least once.
Upvotes: 2
Reputation: 12132
Yes, very much so. If you don't want that you need to change the algorithm completely, perhaps recording the numbers you've printed.
Upvotes: 1