1

what is the solution of this by python 3 ?

Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]. 
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
HasanShovon
  • 59
  • 1
  • 1
  • 5
  • 1
    use combinations to combine elements together and find the sum – Jean-François Fabre Apr 10 '18 at 19:53
  • Agreed. @Jean-FrançoisFabre Python only knows to do what you tell it to do. I'm unaware of such a combination search unless you define it. – Michael Apr 10 '18 at 19:55
  • 3
    Welcome to StackOverflow! Please consider reading this documentation: [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822) – kmote Apr 10 '18 at 19:57
  • 1
    @Michael: `itertools.combinations` taken 2 at a time without replacement. – Prune Apr 10 '18 at 20:14

9 Answers9

8

use itertools.combinations which combines the elements of your list into non-repeated couples, and check if the sum matches. If it does, print the positions of the terms:

import itertools

integer_array = [2, 8, 4, 7, 9, 5, 1]
target = 10
for numbers in itertools.combinations(integer_array,2):
    if sum(numbers) == target:
        print([integer_array.index(number) for number in numbers])
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • why you used itertools.combinations(lst,2) ? – HasanShovon Apr 10 '18 at 20:16
  • to generate non-repeating couples, like asked. – Jean-François Fabre Apr 10 '18 at 20:18
  • 1
    on test case: list = [3,3], target = 6, your code is returning index [0,0], but the ans will be [0,1]. – tulsi kumar Aug 19 '19 at 11:15
  • @HasanShovon - ```itertools.combinations(lst,2)``` is going to return the indices of all combinations of 2 numbers from the array ```lst``` that sum up to the target. If you change 2 to 3, ```itertools.combinations(lst,3)``` is going to return the indices of all combinations of 3 numbers from the array ```lst``` that sum up to the target. –  Nov 20 '19 at 21:17
5

This function iterates through all the numbers in the list and finds the sum with other numbers. If the sum is equal to the target, it returns the indices

def indices_sum(nums,target):
    for i in range(len(nums)):
        for j in range(i+1,len(nums)):
            if nums[i]+nums[j] == target: return(i,j)
4

The main problem with solutions testing all possible couples (with imbricated loops or itertools.combinations) is that that are O(n^2), as you basically test all possible combinations of two elements among n (there are n*(n-1)/2 such combinations) until you find a valid one.

When n is large, you will need a more efficient algorithm. One possibility is to first sort the list (this is O(n * log(n))), finding the solution can then be done directly in O(n), which gives you a solution in O(n * log(n)).


We sort the list first, then add the first (smallest) and last (greatest) values. If the sum is too large, we can remove the largest value. If it's too small, we remove the smallest one, until we reach the exact sum.

We can use a collection.deque to efficiently remove values at any end of the list.

In order to retrieve the indices, we keep them besides the values in tuples.

from collections import deque


def find_target(values, target):

    dq = deque(sorted([(val, idx) for idx, val in enumerate(values)]))

    while True:
        if len(dq) < 2:
            raise ValueError('No match found')

        s =  dq[0][0] + dq[-1][0]

        if s > target:
            dq.pop()
        elif s < target:
            dq.popleft()  
        else:
            break
    return dq[0], dq[-1]



values = [23, 5, 55, 11, 2, 12, 26, 16]
target = 27

sol = find_target(values, target)

print(sol)
# ((11, 3), (16, 7))
# 11 + 16 == 27, indices 3 and 7

print(sol[0][1], sol[1][1])
# 3 7
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
4

We can do the following:

numbers = [2, 7, 11, 15]
target =9
for x in numbers:
    for y in numbers:
        if x+y==target:
            print(x,y)
LaraRaraBoBara
  • 628
  • 1
  • 6
  • 15
1

Either of following approaches can be used to finding two numbers numbers in a list that add up to a given target value:

number_range = [1184.27, 1283.89, 3987.02, 6012.98, 5678.75, 9897.77]

target = 10000

1. Using for loop:

for a in number_range:
for b in number_range[number_range.index(a):]:
if a + b == target:
print(a,b)

Output:
3987.02 6012.98

2. Using itertools.combinations

itertools.combinations(iterable, r)

This approach combines the list items into unique groups of r (here 2), and check if the sum matches the target.

import itertools

for numbers in itertools.combinations(number_range,2):
if sum(numbers) == target:
print(numbers)

Output:
(3987.02, 6012.98)

  • The question is to find the indices of the numbers, and not the numbers themselves. May be you can improve your solution by fetching the index of the numbers that give the solution – Sarfraaz Ahmed Mar 25 '22 at 11:00
0

This question has 2 parts:

  1. Retrieving the 2 items in a list which equate to the target
  2. Retrieving their index value

    def get_index_for_target(nums, target):

    for x in nums:
        for y in nums:
            if x + y == target:
                return (nums.index(x), nums.index(y))
    
Hani Zion
  • 11
  • 4
0

For each entry in the list, check whether there's any other numbers in the list after that number that add up to the target. Since a+b = target is equivalent to b = target - a, you can just take each element, look at all the numbers after that element, and check whether they are target - element. If so, return the indices.

for index,num in  enumerate(nums):
    if target-num in nums[index+1:]:
        return(index, nums.index(target-num))
Acccumulation
  • 3,491
  • 1
  • 8
  • 12
0

We can use to pointers, at the beginning and at the end of the list to check each index by the sum of the two numbers, looping once.

def sumOfTwo(array, target):
    i = 0
    j = len(array) - 1
    while i < j:
      add = array[i] + array[j]
      if add == target:
        return True
      elif add < target:
        i += 1
      else:
        j -= 1
    return False 

input -> [1, 2, 3, 4] -> target: 6

 i->    <-j
[1][2][3][4]  if i + j = target return True 
              if i + j < target increase i
              else decrease j

Note: In a edge case, a guard of check before the loop, in case: target is a negative value, list is empty, target is null.

Israel Manzo
  • 217
  • 3
  • 6
0
def indices_sum(nums,target):
    for i in range(0,len(nums)):
        for j in range(i+1,len(nums)):
            if nums[i]+nums[j] == target: 
                print(nums[i],nums[j])
nums=[1,2,3,4,5]
target=5
indices_sum(nums,target)
  • 4
    Welcome to Stack Overflow. Please explain how your code answers the specific question being asked. See How to Answer https://stackoverflow.com/help/how-to-answer – cards Aug 25 '21 at 20:55