Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

function returning None (functional programming)

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading