简体   繁体   English

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

[英]Given an array find element pairs whose sum is equal to the given sum and return the sum of their indices

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; 2 + 5 = 7→索引2 + 5 = 7;

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

7 + 4 = 11 → Return 11; 7 + 4 = 11→返回11;

Thanks in Advance! 提前致谢!

you can try using a nested loop : 您可以尝试使用嵌套循环:

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)

output: 输出:

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

You could use itertools for easily checking sum for combinations like, 您可以使用itertools轻松检查combinations sum ,例如,

>>> 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]

You could take a different approach by calculating the difference then checking if each element is present in the first array or not. 您可以通过计算差异然后检查第一个数组中是否存在每个元素来采用不同的方法。

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

output 输出

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

To remove the duplicates, its always easy to take a frozenset of the indices tuple 要删除重复项,总是很容易对索引元组进行frozenset设置

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

暂无
暂无

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

相关问题 给定一个由 N 个整数组成的数组和一个整数 K,找出该数组中总和等于 K 的元素对的数量 - Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K 如何在整数数组中查找其总和在给定值范围内的所有有序元素对 - How to find all ordered pairs of elements in array of integers whose sum lies in a given range of value 从4个给定的数组(未排序)中,找到每个数组的元素,其总和等于某个数字X. - From 4 given arrays(not sorted), find the elements from each array whose sum is equal to some number X 总和小于给定总和的最大子集 - Largest Subset whose sum is less than equal to a given sum 计算数组中总和等于给定总和的元素对(但是)在单次迭代中完成(!) - Count pairs of elements in an array whose sum equals a given sum (but) do it in a single iteration(!) 查找数组中总和为给定值的所有元素对 - Find all pairs of elements within an array that sum up to a given value 给定索引列表的数组的部分和 - Partial sum over an array given a list of indices 找到一个数组中最短的子数组,其给定数组中索引的总和等于子数组元素的总和 - Find the shortest subarray in an array, whose sum of indexes in the given array equals the sum of the elements of the subarray 返回一个数组,其中新元素是给定数组中具有相同值的索引之间的距离总和 - Return an array where the new elements are the sum of sum of distances between indices with same value in a given array 如何找到它们的总和等于给定数字的数字? - How to find the numbers that their sum equal to a given number?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM