繁体   English   中英

查找列表中不同于x的所有数字对的最快方法

[英]The fastest way to find all pairs of numbers in a list that differ not more than x

我现在拥有的:

d = 0
res = 0
newlist = []
l = [4, 1, 6, 1, 1, 1]

for el in range(len(l)):
    for j in range(len(l)):
        if abs(l[el] - l[j]) <= d and el != j and el not in newlist and j not in newlist:
            newlist.append(el)
            newlist.append(j)
            res += 1

print(res)

它运作良好并返回2是正确的(1,1; 1,1),但需要太多时间。 如何让它更快地工作? 谢谢。

例如,如果list = [1,1,1,1]和d = 0,则会有2对,因为您只能使用每个数字一次。 不允许使用(a,b)和(b,c),(a,b)与(b,a)是同一对...

对列表进行排序,然后浏览它。

一旦你对列表进行了排序,你就可以贪婪:采用最早的一对,然后是下一个,然后是下一个......你将得到最大数量的有效对。

def get_pairs(lst, maxdiff):
    sl = sorted(lst) # may want to do lst.sort() if you don't mind changing lst
    count = 0
    i = 1
    N = len(sl)
    while i < N:
        # no need for abs -- we know the previous value is not bigger.
        if sl[i] - sl[i-1] <= maxdiff:
            count += 1
            i += 2 # these two values are now used
        else:
            i += 1
    return count

这里有一些代码可以对它进行基准测试:

print('generating list...')
from random import randrange, seed
seed(0) # always same contents
l = []
for i in range(1000000):
    l.append(randrange(0,5000))

print('ok, measuring...')

from time import time

start = time();
print(get_pairs(l, 0))
print('took', time()-start, 'seconds')

结果(列表中有100万个值):

tmp$ ./test.py 
generating list...
ok, measuring...
498784
took 0.6729779243469238 seconds

您可能希望单独计算所有对,然后收集所需的对。

def get_pairs(l, difference):
    pairs = []
    # first compute all pairs: n choose 2 which is O(n^2)
    for i in xrange(len(l)):
        for j in xrange(i+1, len(l)):
            pairs.append((l[i], l[j]))

    # collect pairs you want: O(n^2)
    res = []
    for pair in pairs:
        if abs(pair[0] - pair[1]) <= difference:
            res.append(pair)
    return res

>>> get_pairs([1,2,3,4,2], 0)
>>> [(2, 2)]
>>> get_pairs([1,2,3,4,2], 1)
>>> [(1, 2), (1, 2), (2, 3), (2, 2), (3, 4), (3, 2)]

如果要从结果中删除重复项,可以在使用set(res)返回res列表之前将其转换为set(res)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM