Recursion Visualizer

2 min read Original article ↗

Visualize a recursive function


Loading libraries...

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

virfib(3)

def count_partitions(n, m):
    if n == 0:
        return 1
    elif n < 0:
        return 0
    elif m == 0:
        return 0
    else:
        with_m = count_partitions(n-m, m)
        without_m = count_partitions(n, m-1)
        return with_m + without_m

count_partitions(4, 2)

def sum_digits(n):
    if n < 10:
        return n
    else:
        last = n % 10
        all_but_last = n // 10
        return last + sum_digits(all_but_last)

def luhn_sum(n):
    if n < 10:
        return n
    else:
        last = n % 10
        all_but_last = n // 10
        return last + luhn_sum_double(all_but_last)

def luhn_sum_double(n):
    last = n % 10
    all_but_last = n // 10
    luhn_digit = sum_digits(last * 2)
    if n < 10:
        return luhn_digit
    else:
        return luhn_digit + luhn_sum(all_but_last)
    

luhn_sum(5106)


Tip: Add &hide_function=true to hide the function code.

👋🏻 Are you comfortable publicly sharing your visualizations? I'd love to see how folks are using this tool. Post a link in the discussions or @ me on social media (Twitter, Mastodon)

Source code on Github. Thank you @carlsborg for the rcviz library.