K.U
K.U

Reputation: 303

Exit function after if

This maybe a stupid question, but I don't kow how to exit the function below after if statement. This code is written in python

def subset_sum(numbers, target, partial=[]):
    s = sum(partial)

    # check if the partial sum is equals to target
    if s == target:
        print("sum(%s)=%s" % (partial, target))
        print("True")
        return

    if s > target:
        return  # if we reach the number why bother to continue
    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i + 1:]
        subset_sum(remaining, target, partial + [n])

def main():
    print(subset_sum([10, 7, 6, 3], 13))

main()

The output is

sum([10, 3])=13
True
sum([7, 6])=13
True
None

What I need is when sum([10,3)]==13, the function will print

sum([10, 3])=13
True

and then end.

Upvotes: 0

Views: 238

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1125268

You are printing the return value of the function. Your function returns None (the default return value), so that is what is printed.

Drop the print() function call, just call the function and leave it at that:

def main():
    subset_sum([10, 7, 6, 3], 13)

Next, your recursive function continues to search for additional solutions, because you don't flag when a solution has been found.

You could return True when you have found a solution, then stop all further searches when a recursive call is true:

def subset_sum(numbers, target, partial=None):
    partial = partial or []
    s = sum(partial)

    # check if the partial sum is equals to target
    if s == target:
        print("sum(%s)=%s" % (partial, target))
        print("True")
        return True

    if s > target:
        return False # if we reach the number why bother to continue
    for i in range(len(numbers)):
        n = numbers[i]
        remaining = numbers[i + 1:]
        if subset_sum(remaining, target, partial + [n]):
            # solution found, stop searching
            return True

    return False

Upvotes: 2

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137547

Your function is just returning, which means it returns None. This is a problem when you're calling the function recursively, because the parent doesn't know whether it should continue recursing or not.

You should instead return a value that tells the parent call whether or not it should return or continue.

Upvotes: 0

Related Questions