Mohamed Faid
Mohamed Faid

Reputation: 9

How can I generate a large set of random numbers without collision on Python?

From my class project I found some difficulties to create a set of random numbers and after that to create a fresh random numbers without having any collision if possible.

I tried this program already

import random

def random_sample(count, start, stop, step=1):
    def gen_random():
        while True:
            yield random.randrange(start, stop, step)

    def gen_n_unique(source, n):
        seen = set()
        seenadd = seen.add
        for i in (i for i in source() if i not in seen and not seenadd(i)):
            yield i
            if len(seen) == n:
                break

    return [i for i in gen_n_unique(gen_random,
                                    min(count, int(abs(stop - start) / abs(step))))]

Upvotes: 0

Views: 973

Answers (3)

etch_45
etch_45

Reputation: 792

Option 1

Try this method to generate a random int between the lower and upper bound.

import random

def rand_int(lower, upper):
     return random.randint(lower, upper)

Output:

>>> rand_int(1,1000)
432
>>> rand_int(1,1000)
718

Then use it as part of a list and put a check in your code to see if the value already exists.

>>> a = [rand_int(1,10), rand_int(1,11), rand_int(1,17)]
>>> a
[6, 10, 14]

Option 2

Using numpy and math modules, I observed that a unique list was generated for a small sample as follows.

import numpy as np
import math

x = np.random.rand(5)
for i in range(len(x)):
     print(math.floor(x[i]*100))

Output:

95
55
67
71
68 

Upvotes: 0

quamrana
quamrana

Reputation: 39404

You could create an empty set and then fill it checking if the length is correct:

def random_sample(count, start, stop, step=1):
    random_list = set()
    
    while len(random_list) < count:
        random_list.add(random.randrange(start, stop, step))
    return list(random_list)

print(random_sample(count, start, stop, step))

Note that this code will enter an infinite loop for certain combinations of parameters. i.e. if you ask for more number than there are in a range.

Upvotes: 0

Keredu
Keredu

Reputation: 388

You could create an empty list and then fill it checking if the number is already in the list or not:

random_list = []
while len(random_list) < N:
    number = random.randrange(start, stop, step)
    if not number in random_list:
        random_list.append(number)
print(random_list)

Being N how many numbers must be inside the list.

Upvotes: 1

Related Questions