﻿ Python: Find the first two elements of a given list whose sum is equal to a given value - w3resource

# Python: Find the first two elements of a given list whose sum is equal to a given value

## Python Itertools: Exercise-25 with Solution

Write a Python program to find the first two elements of a given list whose sum is equal to a given value. Use the itertools module to solve the problem.

Sample Solution:

Python Code:

``````import itertools as it
def sum_pairs_list(nums, n):
for num2, num1 in list(it.combinations(nums[::-1], 2))[::-1]:
if num2 + num1 == n:
return [num1, num2]

nums = [1,2,3,4,5,6,7]
n = 10
print("Original list:",nums,": Given value:",n)
print("Sum of pair equal to ",n,"=",sum_pairs_list(nums,n))

nums = [1,2,-3,-4,-5,6,-7]
n = -6
print("Original list:",nums,": Given value:",n)
print("Sum of pair equal to ",n,"=",sum_pairs_list(nums,n))
```
```

Sample Output:

```Original list: [1, 2, 3, 4, 5, 6, 7] : Given value: 10
Sum of pair equal to  10 = [4, 6]
Original list: [1, 2, -3, -4, -5, 6, -7] : Given value: -6
Sum of pair equal to  -6 = [1, -7]
```

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Next: Write a Python program to find the nth Hamming number. User itertools module.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## Python: Tips of the Day

Inverts a dictionary with non-unique hashable values:

Example:

```def tips_collect_dictionary(obj):
inv_obj = {}
for key, value in obj.items():
inv_obj.setdefault(value, list()).append(key)
return inv_obj
ages = {
"Owen": 25,
"Jhon": 25,
"Pepe": 15,
}
print(tips_collect_dictionary(ages))
```

Output:

```{25: ['Owen', 'Jhon'], 15: ['Pepe']}
```

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook