python - 如果列表中的数字等于n,则打印出它们的索引

标签 python

任务:

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] and n = 7

output: 11

since the perfect pairs are (4,3) and (2,5) with indices 1 + 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/

相关文章:

python - 类型错误 : '_curses.curses window' object is not callable

python - 识别时间序列何时通过图表和表格中的阈值

python - 如何在 chromedriver 中屏蔽视频

python - 如何计算python中给定字符串中的空格数

python - 使用 Python 的 `dict.fromkeys` 将新值传递给每个键

python - 将表数据抓取到 .csv 中

python - 访问传递给 argparse 参数的选项?

python - 对于 MNIST 图像,前馈 ANN 的测试精度一直停留在 42%

python - 图像比较算法

Python numpy.random.normal