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

Why doesn't my recursive algorithm return "None"

I have the following for my first function (array defined under function):

def test(array):
    if len(array) == 1:
        return 1
    return test(array[: -1]))

array = [1, 2, 3]
test(array)

It returns:

1

What I thought was happening was that this 1 was being returned up through the two recursive calls until it is outputted to the GUI when it is returned to the original call.

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

I wrote a modified second function where I replace "return test(array[: -1])" with "return print(test(array[: -1])" to confirm by belief, but I get the following output:

1
None

So shouldn’t I receive a "None" or some kind of error instead of a 1 in the first function’s output? What does "None" here actually mean?

>Solution :

Your first function is working as it should. In the first function you are recursively removing the last element of the array until the array has only one element inside, and when that is true it returns 1.

When you changed return test(array[: -1]) for return print(test(array[: -1]) you are now doing 2 things:

  1. You are printing the return value of the function test which as you saw in the first case, will be 1.
  2. You are returning the value of the function print which is None.

So, both scenarios are working accordingly.

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