从两个列表中求和等于x的2个数字的最快方法 [英] The fastest way to find 2 numbers from two lists that in sum equal to x

查看:103
本文介绍了从两个列表中求和等于x的2个数字的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

n = 3
a1 = 0
b1 = 10
a2 = 2
b2 = 2

if b1>n:
    b1=n
if b2>n:
    b2=n

diap1 = [x for x in range(a1, b1+1)]
diap2 = [x for x in range(a2, b2+1)]

def pairs(d1, d2, n):
    res = 0
    same = 0
    sl1 = sorted(d1)
    sl2 = sorted(d2)
    for i in sl1:
        for j in sl2:
            if i+j==n and i!=j:
                res+=1
            elif i+j==n and i==j:
                same+=1
    return(res+same)

result = pairs(diap1, diap2, n)
print(result)

注意:n,a1,b1,a2,b2 可以更改.该代码应从2个列表(每个1个)中找到2个数字,其总和等于n.例如:(a,b)和(b,a)对不同,但是(a,a)和(a,a)对是同一对.因此,我的代码输出是正确的,对于上面的代码是1(1,2),但是对于大的输入,它花费了太多时间.我如何优化它以更快地工作?

NOTE: n, a1, b1, a2, b2 can change. The code should find 2 numbers from 2 lists(1 from each) that in sum equal to n. For example: pairs (a, b) and (b, a) are different but (a, a) and (a, a) is the same pair. So, output of my code is correct and for the code above it's 1(1, 2) but for big inputs it takes too much time. How can I optimize it to work faster ?

推荐答案

使用set()快速查找...

Use set() for fast lookup...

setd2 = set(d2)

请勿尝试所有可能的数字对.确定第一个列表中的一个数字后,说出i,只要看看(n-i)是否在第二个列表中即可.

Don't try all possible number pairs. Once you fix on a number from the first list, say i, just see if (n-i) is in the second set.

for i in sl1:
    if (n-i) in setd2:
        # found match
    else:
        # no match in setd2 for i

这篇关于从两个列表中求和等于x的2个数字的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆