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

时间:2018-04-23 07:56:36

标签: python

任务:

  

您将获得两个参数,一个数组和一个数字。对于所有以2对成对的n的数字,返回其索引的总和。

     

输入是:arr = [1, 4, 2, 3, 0, 5]n = 7

     

输出11

     

因为完美对是(4,3)(2,5),其索引为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还是应该更改整个功能?

4 个答案:

答案 0 :(得分:2)

您可以生成索引组合,而不是生成数组元素的组合。

{{1}}

答案 1 :(得分:0)

您可以使用dictonary映射索引:

def pairwise(arr, n):
    d = {b:a for a,b in enumerate(arr)} #create indexed dict
    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(d[i[0]],d[i[1]])

这里有live example

答案 2 :(得分:0)

不是生成组合并检查它们是否加起来n,而是将列表转换为dict的速度更快,您可以在其中查找加起来n所需的确切数字。对于每个号码x,您可以轻松计算n - x,然后在您的词典中查找该号码的索引。

仅当输入列表中不包含任何重复的数字时才有效。

arr = [1, 4, 2, 3, 0, 5]
n = 7

indices = {x: i for i, x in enumerate(arr)}
total = 0
for i, x in enumerate(arr):
    remainder = n - x
    if remainder in indices:
        idx = indices[remainder]
        total += i + idx

# the loop counts each pair twice (once as [a,b] and once as [b,a]), so
# we have to divide the result by two to get the correct value
total //= 2

print(total)  # output: 11

如果输入 包含重复的数字,则您必须重写代码以在dict中存储多个索引:

import collections

arr = [1, 4, 2, 3, 0, 5, 2]
n = 7

indices = collections.defaultdict(list)
for i, x in enumerate(arr):
    indices[x].append(i)

total = 0
for i, x in enumerate(arr):
    remainder = n - x
    for idx in indices[remainder]:
        total += i + idx

# the loop counts each pair twice (once as [a,b] and once as [b,a]), so
# we have to divide the result by two to get the correct value
total //= 2

答案 3 :(得分:0)

你应该在这里使用天真的方法:

  • 使用其indice
  • 处理数组的每个元素
  • 对于此之后的所有元素的每个元素测试(以避免重复),它们的总和是否是预期数量,以及是否添加了它们的索引总和

代码可以是:

def myfunc(arr, number):
    tot = 0
    for i, val in enumerate(arr):
        for j in range(i+1, len(arr)):
            if val + arr[j] == number:
                tot += i + j
    return tot

控制:

>>> myfunc([1, 4, 2, 3, 0, 5], 7)
11
>>> myfunc([2, 4, 6], 8)
2