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,

user2092743
  • 351
  • 1
  • 4
  • 11
  • You can easily visualize recursive function using [recursion-visualiser](https://github.com/sarangbishal/Recursion-Tree-Visualizer) package in Python. Here is how to do it: https://stackoverflow.com/a/60126148/7552117 – Bishal Sarang Feb 08 '20 at 11:26

2 Answers2

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
k4ppa
  • 4,122
  • 8
  • 26
  • 36
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

Bishal Sarang
  • 106
  • 2
  • 5
  • 1
    links are broken – mLstudent33 May 13 '20 at 05:52
  • 1
    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/' ` – mLstudent33 May 13 '20 at 18:00
  • 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 https://bobswift.atlassian.net/wiki/spaces/GVIZ/pages/20971549/How+to+install+Graphviz+software Feel free to open issue on github if any problem arises. – Bishal Sarang May 15 '20 at 07:00