1

I have an integer value of 10 and array list with integer numbers, how can I check if the array contains a sum of two values that give a result 10 ?

x = 10
arr[1, 11, 7, 3, 5, 2]

Example: I need to write script that does this: arr[2] + arr[3] = 10

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
ERM
  • 73
  • 7
  • Does this answer your question? [Algorithm to find which number in a list sum up to a certain number](https://stackoverflow.com/questions/3420937/algorithm-to-find-which-number-in-a-list-sum-up-to-a-certain-number) – Tomerikoo Apr 14 '21 at 10:20

2 Answers2

1

You could try all the options using a nested for loop?

for i, x in enumerate(arr):
    for j, y in enumerate(arr):
        if i == j: # Don't try and add the same number to itself (i.e. arr[2] + arr[2])
           continue  
        elif x + y == 10:
           return True
return False

Alternatively, if all the values are unique you can create a set, and then check for a particular value (10 - value) is in the set:

 s = set(arr)

 for x in s:
     if 10 - x in s:
         return True
return False
Daniel Lee
  • 7,189
  • 2
  • 26
  • 44
1

try this . it will show the numbers in the list which gives the sum

def printPairs(arr, arr_size, sum):
    s=set()
    for i in range(0, arr_size):
        temp = sum-arr[i]
        if (temp in s):
            print("the values in array that gives sum are", str(arr[i]), str(temp))
        s.add(arr[i])
A = [1, 11, 7, 3, 5, 2]
n = 10
printPairs(A, len(A), n)
Scrapper
  • 182
  • 3
  • Okay, thank you very much this is the thing I need. Only have to figure out how to show the indexes from the array as a result – ERM Apr 14 '21 at 10:02