Search code examples
pythonpython-3.xnumpysum

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. For Eg: - ([1,2,3],4) should return [0,2] because 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. The Combination of integers are [[2, 2], [2, 3], [2, 3]] and the sum of those individual lists correspondingly are [4 5 5]. I want to print the indices of 4(Which is the target value)

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.


Solution

  • Plain python solution:

    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"