Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python stop recursion once solution is found

I have a recursive function which tries to form a certain sum given a list of integers. The function works but it gives me all possible solutions. I want to break out of the recursive function once a solution is found. How can I do that? Below is the (pseudo-)code for the function:

function find_sum(list_of_integers, target_sum, partial_solution):
    if partial_solutions == target_sum:
        return True
    if partial_solution > target_sum:
        return

    for i in range(len(list_of_integers)):
        n = list_of_integers[i]
        remaining = list_of_integers[i+1:]
        find_sum(remaining, target_sum, partial_solution + n)

So I just want to know if the target_sum can be formed by the list of integers, I don't need all the solutions.

like image 306
Koen Avatar asked Dec 20 '22 04:12

Koen


1 Answers

You need to check the return value of the recursive call; if True is returned, propagate that immediately rather than continue to loop:

for i in range(len(list_of_integers)):
    n = list_of_integers[i]
    remaining = list_of_integers[i+1:]
    found = find_sum(remaining, target_sum, partial_solution + n)
    if found:
        return True
like image 154
Martijn Pieters Avatar answered Dec 21 '22 16:12

Martijn Pieters