user5779223 user5779223 - 1 year ago 40
Python Question

How to return the value properly in recurssion with python?

I wish to implement a function which can recurs the input array

and calculate the value of
a_i - a_j
is in
j = i -1
and return a list as output finally. So given an array
[1, 2, 3, 4, 5, 6]
, the result would be
[1, 1, 1, 1, 1]

My code is as follow:

import numpy as np
def recur_diff(array, result_array=None):
l = len(array)
if l > 1:
diff = array[-1] - array[-2]
if result_array is None:
result_array = np.array([diff])

result_array = np.append(result_array, diff)
recur_diff(array[:-1], result_array)
return result_array

But the result returned is
. And if I
print result_array
, the output is what I expect. Do you have any idea? Thanks in advance!


add a return to the recursive call to recur_diff in recur_diff(array[:-1], result_array). Otherwise the results will never be returned back to upper levels

if l > 1:
    # ...
    return recur_diff(array[:-1], result_array)
    return result_array

Just as a hint: instead of manipulating the result_array and pass it to the next level you could compute the next level and merge/work with the result on the current level. In many cases this is cleaner code. (In your example you'd know for sure the returned value is an array, instead of testing for None)