1

I'm learning about recursion and I wrote this (inefficient) n'th Fibonacci number calculator:

def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

I know that in recursion, you can draw so called 'recursion trees'. When I made this simple binary generator:

def binary(length, outstr=""):
    if len(outstr) == length:
        print(outstr)
    else:
        for i in ["0", "1"]:
            binary(length, outstr + i)

I could figure out what this tree looks like: enter image description here

But I cannot figure out the tree of the Fibonacci function! What would that tree look like?

Thanks in advance,

1

2 Answers 2

4

For example fibonacci(4) gives the following recursive tree, because require two function call: fibonacci(3) and fibonacci(2), so every call to the function, call other two functions, until you reach the exit conditions.

            4
           / \
          /   \
         /     \
        3       2
       / \     / \
      /   \   /   \
     2     1 1     0
    / \
   /   \
  1     0
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, just what I needed!
1

You can easily visualize any recursive function using recursion-visualiser package in Python. You just need to add decorator to your function and it does the rest.

Binary String

Let's do it for binary string first.

from visualiser.visualiser import Visualiser as vs

"""
Problem Link: https://stackoverflow.com/questions/33808653/recursion-tree- 
with-fibonacci-python/60126306#60126306
"""

@vs(node_properties_kwargs={"shape":"record", "color":"#f57542","style":"filled", "fillcolor":"grey"})
def binary(length, outstr=""):
     if len(outstr) == length:
          print(outstr)
     else:
          for i in ["0", "1"]:
               binary(length=length, outstr=outstr + i)

binary(length=3,outstr="")
vs.make_animation("binary_string.gif", delay=2)

Here is how output animation looks like binary_string.gif

Also the final tree is saved as : binary_string.png

Fibonacci: Let's visualise it for fib(6)

# Import Visualiser class from module visualiser
from visualiser.visualiser import Visualiser as vs

# Add decorator
@vs(node_properties_kwargs={"shape":"record", "color":"#f57542", "style":"filled", "fillcolor":"grey"})
def fib(n):
    if n <= 1:
        return n
    return fib(n=n - 1) + fib(n=n-2)

def main():
    print(fib(n=6))
    vs.make_animation("fibonacci.gif", delay=2)

if __name__ == "__main__":
    main()

Here is the output which looks much better: animation.gif

Here is the final image of the recursion tree: out.png

Check out more examples at here

3 Comments

links are broken
Do I just need to put this anywhere on the script or in main? os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'
You are required to download graphviz and add graphviz executable to PATH. You can do it manually from environment variables or alternatively add it using the above script . If you are installing from pip then the above process may not work. You may have to do it manually . Here is the link that can help you setup graphviz bobswift.atlassian.net/wiki/spaces/GVIZ/pages/20971549/… Feel free to open issue on github if any problem arises.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.