[英]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.