[英]Python: search a list of numbers in a list of very large numbers, allowing + or - 5 error
情况:
我想做一个匹配:检查一个数字是否在一个数字列表中(非常大的列表,长度超过1e ^ 5甚至2e ^ 5)允许+或 - 5错误
示例:匹配列表中的95 [0,15,30,50,60,80,93] - >列表中的真匹配[0,15,30,50,60,70,80,105,231,123123,12312314,... ] - >假
ps:list没有排序(或者我可以对它进行排序,如果这样可以提高效率)
我试图使用字典(somekey和数字列表)但是当我在列表中进行搜索时它太慢了。
有没有更好的想法? (我需要搜索3000多个数字)
没有排序列表(O(n)时间) :
def search(L, x):
for i in L:
if -5 <= i-x <= 5:
return True
return False
通过排序(O(nlogn)时间排序+ O(logn)时间来搜索) :
def search(L, x):
L.sort()
return fuzzyBinSearch(L, x)
def fuzzyBinSearch(L, x):
mid = len(L)/2
i = L[mid]
if if -5 <= i-x <= 5:
return True
elif i-x > 5:
return fuzzyBinSearch(L[mid+1:], x)
else:
return fuzzeBinSearch(L[:mid], x)
如果您需要进行多次搜索,只需创建一个集并在其中进行搜索即可
>>> L = [0, 15, 30, 50,60,80,93]
>>> S = {i+x for i in L for x in range(-5, 6)}
>>> 95 in S
True
创建set
当然是O(n),但现在查找是O(1)
我喜欢@ inspectorG4dget的答案,但会将其反转:
而不是排序长列表并搜索它(并且必须将它全部保存在内存中),
对短名单(您正在寻找的数字)进行排序,然后遍历长列表,查看每个项目是否与任何搜索项匹配。
这应该更快并且使用更少的内存。 您可能希望使用Python的bisect
模块来执行此操作。
a = set([0, 15, 30, 50,60,80,93])
def match(n):
return bool({n+i for i in range(-5,6)} & a)
print match(95)
a = set([0,15,30,50,60,70,80,105,231,123123,12312314])
print match(95)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.