user5779223
user5779223

Reputation: 1490

How to return the value properly in recursion with python?

I wish to implement a function which can recurs the input array a and calculate the value of a_i - a_j where i is in (len(a)), 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])

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

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

Upvotes: 0

Views: 36

Answers (1)

DomTomCat
DomTomCat

Reputation: 8569

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)
else:
    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)

Upvotes: 1

Related Questions