Python Forum

Full Version: recursive action
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i dont understand how this code works, as per my understanding every time the def function will be called , why it returns a result.

def rabbits(n):
    if n<1:
        return 0
    else:
        if n==0 or n==1:
            return 1
        else:
            return rabbits(n-1)+rabbits(n-2)-rabbits(n-5)
For this, I recommend you get a whiteboard or piece of paper, and draw it out as a tree. Start at the top with the first call. Then write below that any recursive calls. And write below those other recursive calls. When you write them out, I recommend doing it as "rabbits(whatever number)".
(Jun-06-2017, 01:01 PM)elhetch Wrote: [ -> ]i dont understand how this code works, as per my understanding every time the def function will be called , why it returns a result.

def rabbits(n):
    if n<1:
        return 0
    else:
        if n==0 or n==1:
            return 1
        else:
            return rabbits(n-1)+rabbits(n-2)-rabbits(n-5)

    if n<1:
overrides
if n == 0
(Jun-06-2017, 03:46 PM)micseydel Wrote: [ -> ]I recommend you get a whiteboard or piece of paper, and draw it out as a tree. Start at the top with the first call. Then write below that any recursive calls. And write below those other recursive calls.
Or download Thonny
it's has the best way to display recursive calls that i have seen.
When step into debugger,it will show a new window for each recursive call with all values that changing.
(Jun-06-2017, 04:03 PM)snippsat Wrote: [ -> ]Or
I might recommend that for experienced programmers, but struggling aids learning.
(Jun-06-2017, 04:04 PM)micseydel Wrote: [ -> ]I might recommend that for experienced programmers, but struggling aids learning.
Thonny is designed for total beginners,it's really great i use Thonny sometime myself.
I can agree whiteboard or piece of paper is good way to learn without using any tool.
I don't want to hijack this thread, but I would suggest the OP try to do it manually, and definitely use Thonny if any of these are true: they've mastered walking through code and want it automated, they have tried it manually and struggled and need further help, they have successfully done it manually but want to verify it.