任务:
You are given two parameters, an array and a number. For all the numbers that make n in pairs of two, return the sum of their indices.
input is:
arr = [1, 4, 2, 3, 0, 5]
andn = 7
output:
11
since the perfect pairs are
(4,3)
and(2,5)
with indices1 + 3 + 2 + 5 = 11
到目前为止,我已经有了这个,它可以打印出完美的配对
from itertools import combinations
def pairwise(arr, n):
for i in combinations(arr, 2): # for index in combinations in arr, 2 elements
if i[0] + i[1] == n: # if their sum is equal to n
print(i[0],i[1])
输出:
4,3 2,5
但是,有人有关于如何打印完美对的索引的提示吗?我应该使用 numpy 还是应该更改整个函数?
最佳答案
您可以生成索引组合,而不是生成数组元素的组合。
from itertools import combinations
def pairwise(arr, n):
s = 0
for i in combinations(range(len(arr)), 2): # for index in combinations in arr, 2 elements
if arr[i[0]] + arr[i[1]] == n: # if their sum is equal to n
# print(arr[i[0]],arr[i[1]])
# print(i[0],i[1])
s += i[0] + i[1]
# print(s)
return s
关于python - 如果列表中的数字等于n,则打印出它们的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49976015/