Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appending to a list in recursive function

I wrote the following recursive program which finds the combination of numbers which can be added to make the target value:

arr = [1, 2, 2, 3, 5]
target = 8

def comb_sum(arr, current_index, target, result, ans):
    if target == 0:
        print result
        ans.append(result)
        return 0
    if target < 0:
        return 1
    if current_index == len(arr):
        return 1

    result.append(arr[current_index])
    comb_sum(arr, current_index+1, target - arr[current_index], result, ans)
    result.pop()

    comb_sum(arr, current_index+1, target, result, ans)
    return ans



print comb_sum(arr, 0, target, [], [])

Since I am using arr.append() to append the result, I expected the correct output.

Even though the program is correct, I am unable to add a list result to the ans.

What's wrong?

I am expecting this output: [[1, 2, 2, 3], [1, 2, 5], [1, 2, 5], [3, 5]] But instead I get this output: [[], [], [], []]

like image 929
yask Avatar asked Jun 30 '26 14:06

yask


1 Answers

import copy
arr = [1, 2, 2, 3, 5]
target = 8
def comb_sum(arr, current_index, target, result, ans):

if target == 0:
    print result
    ans.append(copy.deepcopy(result) )
    return 0
if target < 0:
    return 1
if current_index == len(arr):
    return 1

result.append(arr[current_index])
comb_sum(arr, current_index+1, target - arr[current_index], result, ans)
result.pop()

comb_sum(arr, current_index+1, target, result, ans)
return ans

print comb_sum(arr, 0, target, [], [])
like image 177
nanjunxiao Avatar answered Jul 03 '26 03:07

nanjunxiao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!