简体   繁体   中英

Check if there are three numbers in the list that add up to target

I need to create a function that takes as input a list of positive numbers and a positive number target and returns True if there are three numbers in the list that add up to the target.

So far I've come up with this:

def subsetSum(l, sum):
    found = False
    for i in range(len(l) - 2):
        for j in range(i + 1, len(l) - 1):
            for k in range(j + 1, len(l)):
                return True
    return found

REPL:

>>> subsetSum([5, 4, 10, 20, 15, 19], 38)
True

So the sum of 4, 15 and 19 equals to 38, which is my target. When I run this code it comes out to be True .

But when I run the following code, it still comes out to be True , although the list of numbers doesn't have three numbers that add up to the target, which is 10.

>>> subsetSum([5, 4, 10, 20, 15, 19], 10)
True

Probably the simplest and the most efficient solution using itertools.combinations :

from itertools import combinations

def subset_sum(lst, target):
    return len(lst) > 2 and any(sum(x) == target for x in combinations(lst, 3))

Examples:

>>> subset_sum([5, 4, 10, 20, 15, 19], 38)
True
>>> subset_sum([10], 38)
False

Just in case you want to stick with your own code, here's how you can fix it:

def subset_sum(l, target):
    if len(l) < 3:
        return False

    for ki, i in enumerate(l):
        for kj, j in enumerate(l):
            for kk, k in enumerate(l):
                # To make sure we sum elements ONLY on different positions
                if kk != kj and kk != ki and kj != ki and i + j + k == target:
                    return True

    return False

This solution isn't very fast, but it works.

You are always returning True. Since python can handle multiple return statements in a function there is no need for the found variable. Get rid of found and at the end return False. You need an if statement to compare sum and the input values, that returns True when the condition is met or False otherwise. Right now your code is essentially a complicated way of returning True, you are simply iterating through abstract values, not assigning those values to anything and then returning True before returning found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM