Search code examples
pythonalgorithmpython-2.7data-structurespython-itertools

How to iterate and sum each element in a list with another to find a number?


I was taking a programming challenge and this question encountered, I somehow got stuck with it. I was given a list: [10, 13, 15, 18, 20, 15] And I had to find if the sum of any element in this would provide a result 30 and output should be the count As we could see we have two possibilities, 10+20 = 30 and 15+15, so the count is 2. But how to do it, should it be using for loop or itertools or any slicing or functional solution?


Solution

  • You can use itetools.combinations and a generator expression within sum :

    >>> my_list=[10, 13, 15, 18, 20, 15]
    >>> from itertools import combinations
    >>> sum(i+j==30 for i,j in combinations(my_list,2))
    2
    

    And if you want that items too you can use a list comprehension :

    >>> [(i,j) for i,j in combinations(my_list,2) if i+j==30]
    [(10, 20), (15, 15)]