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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With