User007
User007

Reputation: 17

python: Summing up two numbers of a list

This is what I get so far, How can I make it return a False when there is no such values?

def pairSum(l, s):
    a = 0
    b = 1
    for i in l:
        if l[a]+l[b] == s:
            return True
        a=a+1
        b=b+1

Edit: I just realized that this function would only find two consecutive numbers that add to s. I was meant to create a function that determines if any two numbers in a list add up to s, not two consecutive numbers. Sorry for the misleading information.

Upvotes: 0

Views: 100

Answers (1)

pythonic833
pythonic833

Reputation: 3224

f = lambda x,y: x+y

def func(l, s):
    for i in range(len(l)-1):
        if f(l[i],l[i+1]) == s:
            return True
    return False

This will return True if the addition of two consecutative numbers of the list results in s and False otherwise.

If you want to check if the addition of any two numbers in l adds to s then

from itertools import combinations
def sumPairs(l, s):
    for a, b in combinations(lst, 2):
        if a+b == s:
            return True
    return False 

Upvotes: 1

Related Questions