How do generate random numbers, while avoiding numbers already used

给你一囗甜甜゛ 提交于 2019-12-11 05:38:35

问题


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 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.


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



回答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.




回答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.




回答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)]


来源:https://stackoverflow.com/questions/7033542/how-do-generate-random-numbers-while-avoiding-numbers-already-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!