I have encountered this problem many times. The idea of the example recursion is to generate all combination of characters by choosing one character of each element from the input array. Here is working example:
def gen_comb(input_arr, result, index, curr_comb):
if len(curr_comb) == len(input_arr):
result.append(curr_comb)
return
for letter in input_arr[index]:
gen_comb(input_arr, result, index + 1, curr_comb + letter)
return result
print(gen_comb(input_arr=['abc', 'def'], result=[], index=0, curr_comb=""))
And here is the output: ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']. The problem occurs when slightly changing the above code:
def gen_comb(input_arr, result, index, curr_comb):
if len(curr_comb) == len(input_arr):
result.append(curr_comb)
return
for letter in input_arr[index]:
curr_comb += letter
gen_comb(input_arr, result, index + 1, curr_comb)
return result
The only difference is adding curr_comb += letter outside the method signature. In this case the error is IndexError: list index out of range but there is similar examples with wrong result.
The question is:
What is the difference between passing an expression to a recursive function and calculating the expression before to pass to the function?
curr_comb + letterdoesn't modifycurr_combbutcurr_comb += letterdoes.