user5779223 - 1 year ago 50

Python Question

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

`a`

`a_i - a_j`

`i`

`(len(a))`

`j = i -1`

`[1, 2, 3, 4, 5, 6]`

`[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

But the result returned is

`None`

`print result_array`

Answer Source

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`

)