Skip to content Skip to sidebar Skip to footer

How Do Generate Random Numbers, While Avoiding Numbers Already Used

How do i generate random numbers but have the numbers avoid numbers already used. I have a TXT file with thousands of sets of numbers and i need to generate a series of random numb

Solution 1:

You could load up all previously found random numbers into a dictionary, then just check whether new_random in dictionary, and if it is try a new random number.

For the second party, say your ten digit number is stored in variable ten_digits.

ten_digits = '1234567890'

you can break this up into 5 two digit numbers by doing

[x + y for x, y in zip(ten_digits[::2], ten_digits[1::2]
>>> ['12', '34', '56', '78', '90']

Solution 2:

If you need to maintain the file (which I think you do, in order to add new numbers), I would suggest you to "forget" using a plain text file and use SQLite or any other embedded DB that is backed up in a file, as you probably don't want to load all the numbers in memory.

The "feature" (or better said, data structure) you want from SQLite is a B-Tree, so you can retrieve the numbers fast. I'm saying this, because you could also try to find a library that implements B-Trees, and then you wouldn't need SQLite.


Solution 3:

Are you using the numbers as IDs? You should probably look into using a hash table.

http://en.wikipedia.org/wiki/Hash_table

I'm not terribly familiar with Python but I'm sure there is a substring function you can give it (as arguments) an index to start the substring and the number of characters to copy.


Solution 4:

If you your list is relatively small you could load it into a set and check against that:

random_number not in number_set

To split the number you could use slices:

s='0102030405'
n=2
result = [s[i:i+n] for i in range(0, len(s), n)]

Post a Comment for "How Do Generate Random Numbers, While Avoiding Numbers Already Used"