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.

Previous: Write a Python program to find the maximum length of a substring in a given string where all the characters of the substring are same. Use itertools module to solve the problem.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/itertools/python-itertools-exercise-25.php