给定一个数组,找到总和等于给定总和的元素对,并返回其索引的总和

时间:2019-09-16 04:56:39

标签: python algorithm pairwise

嗨,大家在问题中已经读到了,我试图在数组中找到等于给定总和的元素对,并返回它们各自索引的总和。

我能够返回给定总和的元素对,但未能返回其索引的总和。这是我的代码:

arr = [1, 4, 2, 3, 0 , 5]
sum = 7

x = min(arr)
y = max(arr)

while x < y:
    if x + y > sum:
        y -= 1
    elif x + y < sum:
        x += 1
    else:
        print("(", x, y, ")")
        x += 1

我的输出:

( 2 5 )    
( 3 4 )

这是我需要进一步做的事情:

2 + 5 = 7→索引2 + 5 = 7;

3 + 4 = 7→索引3 +1 = 4;

7 + 4 = 11→返回11;

预先感谢!

3 个答案:

答案 0 :(得分:0)

您可以尝试使用嵌套循环:

arr = [1, 4, 2, 3, 0 , 5]
sums = 7
tlist = []
for i in range(len(arr)):
    for j in range(len(arr)-1):
        if (i!=j) and ((arr[i] + arr[j+1]) == sums):
            if (i,j+1) not in tlist and (j+1,i) not in tlist:
                tlist.append((i,j+1))
                print("index ->",i,"   ",j+1)
                print("sum=", i+j+1)

输出:

index -> 1     3
sum= 4
index -> 2     5
sum= 7

答案 1 :(得分:0)

您可以使用itertools来方便地检查sum中的combinations,例如

>>> import itertools
>>> num = 7
>>> for a,b in itertools.combinations(arr, 2):
...   if a + b == num:
        aindex, bindex = arr.index(a), arr.index(b)
...     indices_sum = aindex + bindex
...     print('[element sum]: {} + {} = {} [indices sum]: {} + {} = {}'.format(a, b, a + b, aindex, bindex , indices_sum))
... 
[element sum]: 4 + 3 = 7 [indices sum]: 1 + 3 = 4
[element sum]: 2 + 5 = 7 [indices sum]: 2 + 5 = 7
>>> arr
[1, 4, 2, 3, 0, 5]

答案 2 :(得分:0)

您可以通过计算差异然后检查每个元素是否存在于第一个数组中来采用不同的方法。

arr = [1, 4, 2, 3, 0, 5]
the_sum = 7

diff = [the_sum - x for x in arr]
for idx, elem in enumerate(diff):
    try:
        index = arr.index(elem)
        sum_of_indices = idx + index
        print("{} + {} = {}".format(idx, index, sum_of_indices))
    except ValueError:
        pass

输出

1 + 3 = 4
2 + 5 = 7
3 + 1 = 4
5 + 2 = 7

要删除重复项,总是很容易选取frozenset个索引元组

a = [(2,1), (1,2), (3,2), (2,3)]
{frozenset(x) for x in a} # {frozenset({2, 3}), frozenset({1, 2})}