GithubHelp home page GithubHelp logo

bishalsarang / recursion-tree-visualizer Goto Github PK

View Code? Open in Web Editor NEW
105.0 4.0 18.0 6.39 MB

A simple python package that helps to visualise any recursive function by adding a single line of code.

Home Page: https://pypi.org/project/recursion-visualiser/

License: MIT License

Python 98.81% Dockerfile 1.19%
recursion recursion-tree recursion-tree-visualiser recursion-tree-visualizer visualiser visualization hacktoberfest hacktoberfest2020

recursion-tree-visualizer's Introduction

Recursion Visualiser

PyPI downloads Stars Forks

Recursion visualiser is a python tool that visualizes recursion tree with animation and draws recursion tree for recursive function. It works with almost any type of recursive function. Just add the recursion-visualiser decorator to your function and let it do the rest of the work.

Installation

1. Installing graphviz

Windows

The only dependency for recursion visualiser is Graphviz

  • Download graphviz binary
  • Add graphviz bin to path manually or by adding the following line on your script. Change the installation directory according to your installation path
# Set it to bin folder of graphviz  
os.environ["PATH"] += os.pathsep +  'C:/Program Files (x86)/Graphviz2.38/bin/'  

Ubuntu

  • Install graphviz
 sudo apt install graphviz

The instructions to install graphviz for other operating system is available here

2. Installing recursion-visualiser

The easiest way to install recursion-visualiser package is from pypi

pip install recursion-visualiser

An alternative way is to clone the repository and install all the requirements.

pip install -r requirements.txt

Alternative Installation using Docker

If you have docker and docker-compose installed then you can install recursion-tree-visualiser using Docker and docker-compose.yml file

  1. Download Docker file from repo
curl https://raw.githubusercontent.com/Bishalsarang/Recursion-Tree-Visualizer/master/Dockerfile --output Dockerfile
  1. Download docker-compose.yml
curl https://raw.githubusercontent.com/Bishalsarang/Recursion-Tree-Visualizer/master/docker-compose.yml --output docker-compose.yml
  1. Start docker container
CURRENT_UID=$(id -u):$(id -g) docker-compose up
  1. Run any python scripts and run using
docker-compose exec vs python fibonacci.py

Usage

The preferred way to import the decorator class from the package is as:

from visualiser.visualiser import Visualiser as vs

1. Fibonacci

Let's draw the recursion tree for fibonacci number.
Here is how the simple code looks like

def fib(n):  
    if n <= 1: 
        return n 
    return fib(n - 1) + fib(n - 2)  

print(fib(6))  

Now we want to draw the recursion tree for this function. It is as simple as adding a decorator

# Author: Bishal Sarang

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

# Add decorator
# Decorator accepts optional arguments: ignore_args , show_argument_name, show_return_value and node_properties_kwargs
@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():
    # Call function
    print(fib(n=6))
    # Save recursion tree to a file
    vs.make_animation("fibonacci.gif", delay=2)


if __name__ == "__main__":
    main()

Here are the changes required:

  • Add decorator Visualiser which accepts optional arguments ignore_args, show_argument_name and 'show_return_value'
  • Change every function calls to pass as keyword arguments.
  • Make_animation

The output image are saved as "fibonacci.gif" and "fibonacci.png"

Here is how the recursion tree looks like:
Animation: enter image description here

enter image description here

Support

If you like this project and want to support it, consider buying me a coffee!

Buy Me A Coffee

Thank you for your support!

TODO:

  • Minimal working version
  • Upload package to pypi
  • Support animation
  • Add node styles
  • Support aliasing for function name
  • Show repeated states
  • Support node_color, backgroundcolor etc
  • Refactor
  • Handle base cases
  • Make more beautiful trees

recursion-tree-visualizer's People

Contributors

bishalsarang avatar sachin2uinstructor avatar shresthalucky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

recursion-tree-visualizer's Issues

Write Documentation

Looking for someone to write documentation regarding attributes to customize figure

Refactor

  • Refactor the code by following PEP conventions and guidelines.

Return value

Hi, nice project, it'd be great if you can show the return value from each recursive call.

Unexpected Result

Hello! First of all I think this is a really interesting little tool. I'm thinking about launching a youtube channel where I cover solutions to common interview questions in depth and this could potentially be very useful.

I've got the package installed and working correctly (ran it on fibonacci demo and got the expected result) but when I used it with one of my own functions I got something unexpected.

I've included the code I was running and the output image. The code is for generating all permutations over an input array. The output graph is a series of disconnected components which doesn't make sense to me.

Screen Shot 2020-10-31 at 2 52 36 PM

permutations

no output of .png nor .gif

Hi,

I used this library for a fibonacci project and it worked great.
But now I want to use it for a small function that finds all combinations of a list (recursive).
I am not getting any output of the gif nor png.
It runs, but there is no output

from visualiser.visualiser import Visualiser as vs

@vs(node_properties_kwargs={"shape": "record", "color": "#f57542", "style": "filled", "fillcolor": "grey"})
def combinations_list(colors):
    '''
    https://www.w3resource.com/python-exercises/list/python-data-type-list-exercise-149.php
    :param colors:
    :return:
    '''
    if len(colors) == 0:
        return [[]]
    result = []
    for el in combinations_list(colors[1:]):
        temp = el + [colors[0]]
        print(f'el:{el}, temp: {temp}')
        result += [el, el + [colors[0]]]
        print(f'res: {result}')
    return result

if __name__=="__main__":
    data = list('1234')
   
    print(combinations_list(data))

Error while writing fibonacci.png

@Bishalsarang installed the script with pip. Then copied the fibonacci code and saved in a name.py file tried to run but it failed to make png file and gif file but it created a folder "frames" and "fibonacci.gif" file. Would you please help me fix the issue?

Code:

# Author: Bishal Sarang

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

# Add decorator
# Decorator accepts optional arguments: ignore_args , show_argument_name, show_return_value and node_properties_kwargs
@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():
    # Call function
    print(fib(n=6))
    # Save recursion tree to a file
    vs.make_animation("fibonacci.gif", delay=2)


if __name__ == "__main__":
    main()

Output:

8
Starting to make animation
Writing fibonacci.png failed
Writing frames....
Error writing frames
Writing gif...
Error saving gif.

Folder Structrue:

issue

Failing when argument is mutated.

Thank you, man, this worked.

This is a great project. I run this with merge sort. This worked but made a gif put all the recursive calls side by side.
fibonacci

It would be great if this would show them like your demo Fibonacci gif

I am a beginner so I don't know how can I modify the script. If I could I would modify the script and contribute to it. I hope you will make this work. But I totally understand if you don't.

Originally posted by @Iftakharpy in #2 (comment)

Issue with visualizing DFS on a binary tree

I am using this code snippet to perform DFS on a binary tree.
The target value does not exist in the tree, so I am expecting to traverse all the nodes.

import os

os.environ["PATH"] += os.pathsep +  'C:/Program Files/Graphviz/bin/'
from visualiser.visualiser import Visualiser as vs

class tree_node():
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def build_tree():

    # leaf nodes
    l1 = tree_node(20)
    l2 = tree_node(21)
    l3 = tree_node(1)

    # internal nodes
    n1 = tree_node(3, l1, l2)
    n2 = tree_node(10, l3, None)

    # root node
    r = tree_node(5, n1, n2)

    return r

root = build_tree()

@vs(node_properties_kwargs={"shape":"record", "color":"#f57542", "style":"filled", "fillcolor":"grey"})
def dfs(node, target):
    if not node:
        return None
    if node.val == target:
        return node
    left = dfs(node.left, target)
    if left: # if target is found, then no need to search the right sub-tree
        return left
    return dfs(node.right, target)

match = dfs(root, 11)
if not match:
    print("not found")
else:
    print("found node: %s" % match)


# Save recursion tree to a file
vs.make_animation("dfs.gif", delay=2)

However, the DFS recursion tree that is generated does not look correct,

dfs

Am I missing something here?

[feature request] adding decorator to control graph properties

similar to node_properties_kwargs that controls the node properties:

self.node_properties_kwargs = node_properties_kwargs

it would be good to have graph_properties_kwargs that controls the graph properties.
For example, background color.
So that it is not hard-coded in the code:

cls.graph = pydot.Dot(graph_type="digraph", bgcolor="#fff3af")

Error Writing Frames - Demo Code Does Not Work

The example code itself does not work. I have added the errors below.

# Author: Bishal Sarang

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

# Add decorator
# Decorator accepts optional arguments: ignore_args , show_argument_name, show_return_value and node_properties_kwargs
@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():
    # Call function
    print(fib(n=6))
    # Save recursion tree to a file
    vs.make_animation("fibonacci.gif", delay=2)


if __name__ == "__main__":
    main()



When you run the above code, it gives this:

8
Starting to make animation
Writing fibonacci.png failed
Writing frames....
Error writing frames
Writing gif...
Error saving gif.

Creates a gif of 0 bytes.

Unexpected behavior

I have graphviz-5.0.1, python 3.10.6, windows 10.
Running the following code,

import os
os.environ["PATH"] += os.pathsep +  'C:/Program Files/Graphviz/bin/'

from visualiser.visualiser import Visualiser as vs

@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)

print(fib(n=3))
# Save recursion tree to a file
vs.make_animation("fibonacci.gif", delay=2)

produces an incorrect png/gif.

fibonacci

fibonacci

Error while writing fibonacci.png

I copied the fibonacci code and saved it as code.py file and tried to run but it failed to make png file and gif file but it created a folder "frames" and "fibonacci.gif" file. Would you please help me fix the issue?

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

# Add decorator
# Decorator accepts optional arguments: ignore_args , show_argument_name, show_return_value and node_properties_kwargs
@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():
    # Call function
    print(fib(n=6))
    # Save recursion tree to a file
    vs.make_animation("fibonacci.gif", delay=2)


if __name__ == "__main__":
    main()

Error:

8
Starting to make animation
Writing fibonacci.png failed
Writing frames....
Error writing frames
Writing gif...
Error saving gif.

Installation:

imageio==2.6.1
pydot==1.4.1
recursion-visualiser==1.0.2

Tried following version of graphviz with above installation:

graphviz-2.50.0 (32-bit)
graphviz-2.50.0 (64-bit)

and also added graphviz bin dir path to system path variable and successfully verified it using dot -V

Question: How to remove main(None) node

When you generate the GIF with the default example, for some reason a node gets generated for the main() function even though main() is not decorated.

Is there a way to avoid this?

Examples

Write examples using Recursion Tree Visualizer as a markdown file to be included in the documentation.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.