function returning None (functional programming)

Question:

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 = upgrade_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?

Asked By: MarnieGrenat

||

Answers:

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)
Answered By: Gaberocksall

To make your function return the a ndarray, you need to add a return statement in the else block of your code where you call the upgrade_array function recursively. Here’s how your code should look like:

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

In your code, the upgrade_array function is called recursively in the else block, but there’s no return statement there, so the returned value of the recursive call is not used and the function ultimately returns None. By adding a return statement, you ensure that the returned value of the recursive call is used and the function returns the expected result.

THIS IS GENERATED BY chatGPT.

Answered By: supergaga