python - 给定一个数组,查找元素对,其总和等于给定的总和,并返回它们索引的总和

标签 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;

提前致谢!

最佳答案

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

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

关于python - 给定一个数组,查找元素对,其总和等于给定的总和,并返回它们索引的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57950597/

相关文章:

python - 获取范围内随机数选择中整数出现次数 N 次

python - 带否定的 re.sub 语法

python - CSV Python 列/行平均值

java - 为什么我的位图排序没有比我的归并排序快无限?

r - 使用另一列中给定条件的两列组合展开 data.table

python - 如何平衡非对称计算机上的消费者负载?

python - elasticsearch-py 和多处理

algorithm - 哪个增长率 log(log *n) 和 log*(log n) 更快?

python - 将两个 numpy 数组转换为成对数组的数组

python - 在成对比较 NxN numpy 数组中找到 N 个最小值?