0

Hey guys as you've read in the question i am trying to find the element pairs in an array equal to the given sum and return the sum of their respective indices.

I was able to return the element pairs for the given sum but failed to return the sum of their indices. Here is my code:

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

My output:

( 2 5 )    
( 3 4 )

This is what i need to do further:

2 + 5 = 7 → Indices 2 + 5 = 7;

3 + 4 = 7 → Indices 3 + 1 = 4;

7 + 4 = 11 → Return 11;

Thanks in Advance!

4

3 回答 3

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
于 2019-09-16T05:11:41.093 回答
0

您可以用于itertools轻松检查类似,sumcombinations

>>> 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]
于 2019-09-16T05:23:51.843 回答
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})}
于 2019-09-16T05:27:24.903 回答