samedi 6 août 2016

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.

Aucun commentaire:

Enregistrer un commentaire