简体   繁体   English

两个数字的索引等于目标值

[英]Indices of two numbers equal to a target value

I was trying to solve this problem and I got stuck at the end.我试图解决这个问题,但最终被卡住了。 This function takes a list consisting of integers and a target value.The indices of any two sum of integers which is equal to the target value should be returned.此 function 采用由整数和目标值组成的列表。应返回等于目标值的任意两个整数和的索引 For Eg: - ([1,2,3],4) should return [0,2] because 3+1=4.例如: - ([1,2,3],4) 应该返回 [0,2] 因为 3+1=4。 My Approach: -我的方法: -

import itertools
import numpy as np
def indices(numbers,target):
    comb_nos = [list(x) for x in itertools.combinations(numbers, 2)]
    print(comb_nos)
    result =np.sum(comb_nos,1)
    print(result)
indices([2,2,3],4)

I managed to get all combinations of the integers in a set of 2(using the itertools module) and use the numpy library to sum it up along an axis of 1. I can't seem to figure out a way to print the indices.我设法获得了一组 2 中的所有整数组合(使用 itertools 模块),并使用 numpy 库沿轴 1 对其进行总结。我似乎无法找到打印索引的方法。 The Combination of integers are [[2, 2], [2, 3], [2, 3]] and the sum of those individual lists correspondingly are [4 5 5] .整数的组合是[[2, 2], [2, 3], [2, 3]]并且这些单独列表的总和相应地是[4 5 5] I want to print the indices of 4(Which is the target value)我想打印 4 的索引(这是目标值)

There are few hints out there but since I have reached almost the ending,I want to know how I could have done it my way.I would appreciate it if anyone could help me solve this.那里几乎没有提示,但由于我已经接近结局,我想知道我怎么能做到这一点。如果有人能帮助我解决这个问题,我将不胜感激。

You can do it without loop by calculating all combinations of pairwise summation of elements using numpy broadcasting and then searching for target using np.argwhere (if your arrays are too large, using itertools might be slightly more efficient as this one calculates every combination twice, however it is faster in the calculations itself):您可以通过使用 numpy 广播计算元素的所有成对总和的所有组合,然后使用np.argwhere搜索目标(如果您的 arrays 太大,使用 itertools 可能会稍微更有效,因为这个计算每个组合两次,但是计算本身更快):

def indices(numbers,target):
  idx = np.argwhere((numbers.T[:,None]+numbers.T)==target)
  return (idx[idx[:,0]<idx[:,1]])
print(indices(np.array([2,2,3]),4))

And if you want to use itertools, you can do it this way:如果你想使用 itertools,你可以这样做:

def indices(numbers,target):
  idx = np.array(list(itertools.combinations(range(len(numbers)),2)))
  return idx[np.flatnonzero(numbers[np.r_[idx]].sum(1) == target)]
print(indices(np.array([2,2,3]),4))

output: output:

[[0 1]]

EDIT : explanation: numbers.T[:,None]+numbers.T creates a matrix of summations of all pairwise combinations of numbers .编辑: 解释: numbers.T[:,None]+numbers.T创建所有成对numbers组合的总和矩阵。 In other words, its [i,j] -th element is numbers[i]+numbers[j] .换句话说,它的第[i,j]个元素是numbers[i]+numbers[j] np.argwhere finds which of those are equal to target . np.argwhere查找其中哪些等于target

idx[:,0]<idx[:,1] is a condition to filter upper triangle of matrix, since lower triangle of matrix is the same pairwise combinations of numbers as upper triangle (eg [0,1] vs. [1,0] ). idx[:,0]<idx[:,1]是过滤矩阵上三角形的条件,因为矩阵的下三角形是与上三角形相同的成对数字组合(例如[0,1][1,0] )。

You can use combinations() from itertools :您可以使用来自itertoolscombinations()

from itertools import combinations


def indices(numbers, target):

    return [[f[0] for f in s] for s in combinations(enumerate(numbers),2)if sum([f[1] for f in s])==target]

print(indices([1, 2, 3, 2, 3, 2],6))

Output: Output:

[[2, 4]]

Plain python solution:普通 python 解决方案:

def indices(nums: List[int], target: int) -> List[int]:
    for i in range(len(nums)):
        for j in range(i+1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i,j]
            else:
                return "no pair in nums list sums to target"

class Solution { public int[] twoSum(int[] nums, int target) { class 解决方案 { public int[] twoSum(int[] nums, int target) {

    int[] ans = new int[2];
   
   for(int i=0;i<nums.length;i++)
    {
        for(int j=i+1;j<nums.length;j++)
        {
            if(nums[i]+nums[j]==target)
            {
                ans[0]=i;
                ans[1]=j;
                break;
            }
        }
    }
return ans;
    
    
}
    
    public static void main(String args[]){ 
        
        Solution sol = new Solution();
        int[] arr = {1,0,2,4,5};
       int[] ans = sol.twoSum(arr, 7);
       
             
       for (int i=0;i<ans.length;i++) {
          
           System.out.println(ans[i]);
         
           
       }
        
                  
    
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM