function returning None (functional programming) [duplicate]
I'm trying to make an functional function and I want it to return an array (ndarray). I don't know why, but my code is returning None. Here's my code:
def upgrade_array(array:np.ndarray, max_value:int, value:int=1):
a = array.copy()
index = value-1
a[index,:] = value
#display(a)
if value==max_value:
return np.array(a)
else:
upgrade_array(array=a, max_value=max_value, value=value+1)
a = np.zeros(shape=(10,5))
b = up开发者_C百科grade_array(array=a, max_value=10)
display(b)
I know the logic behind is ok, since I verified it (using display(a)). How can I make it return the a ndarray?
In your else:
case, the function does not return a value. Sure, the recursive call might, but the original call will not. You need to return
the value up the call chain like so
def upgrade_array(array:np.ndarray, max_value:int, value:int=1):
a = array.copy()
index = value-1
a[index,:] = value
#display(a)
if value==max_value:
return np.array(a)
else:
# notice the change here:
return upgrade_array(array=a, max_value=max_value, value=value+1)
a = np.zeros(shape=(10,5))
b = upgrade_array(array=a, max_value=10)
display(b)
精彩评论