HasanShovon
HasanShovon

Reputation: 59

how to sum two numbers in a list?

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]. 

Upvotes: 1

Views: 41109

Answers (9)

Hisham Shahid
Hisham Shahid

Reputation: 11

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)

Upvotes: 1

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)

Upvotes: 0

Alex Retana
Alex Retana

Reputation: 41

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)

Upvotes: 4

Jean-François Fabre
Jean-François Fabre

Reputation: 140286

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])

Upvotes: 8

Israel Manzo
Israel Manzo

Reputation: 247

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.

Upvotes: 0

Thierry Lathuille
Thierry Lathuille

Reputation: 24288

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

Upvotes: 4

Alvira Swalin
Alvira Swalin

Reputation: 111

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)

Upvotes: 6

Acccumulation
Acccumulation

Reputation: 3591

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))

Upvotes: 0

Hani Zion
Hani Zion

Reputation: 11

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))
    

Upvotes: 0

Related Questions