Issue
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.
I wrote a modified second function where I replace "return test(array[: -1])" with "return print(test(array[: -1])" to confirm by belief:
def test(array):
if len(array) == 1:
return 1
return print(test(array[: -1]))
array = [1, 2, 3]
test(array)
but I get the following output:
1
None
I expected:
1
1
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])
to return print(test(array[: -1])
you are now doing 2 things:
- You are printing the return value of the function
test
which as you saw in the first case, will be 1. - You are returning the value of the function
print
which isNone
.
So, both scenarios are working accordingly.
Answered By - Tiago Duarte
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.