开发者

How do generate random numbers, while avoiding numbers already used

How do i genera开发者_运维百科te 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 numbers while avoiding these.

IE, TXT - 0102030405

my random number needs to avoid this number.

on a side note, how can i split up the TXT 10 digit number into 5, two digit numbers? then how can i generate random numbers based off of that.


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']


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.


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.


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)]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜