惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

I
InfoQ
Hugging Face - Blog
Hugging Face - Blog
月光博客
月光博客
量子位
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
S
SegmentFault 最新的问题
罗磊的独立博客
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 最新话题
T
Threatpost
Cisco Talos Blog
Cisco Talos Blog
The GitHub Blog
The GitHub Blog
V
V2EX
SecWiki News
SecWiki News
P
Privacy & Cybersecurity Law Blog
Forbes - Security
Forbes - Security
T
Troy Hunt's Blog
S
Security @ Cisco Blogs
Martin Fowler
Martin Fowler
Attack and Defense Labs
Attack and Defense Labs
A
Arctic Wolf
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Register - Security
The Register - Security
Blog — PlanetScale
Blog — PlanetScale
The Last Watchdog
The Last Watchdog
T
Tor Project blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cisco Blogs
P
Proofpoint News Feed
O
OpenAI News
Hacker News - Newest:
Hacker News - Newest: "LLM"
小众软件
小众软件
雷峰网
雷峰网
H
Heimdal Security Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Stack Overflow Blog
Stack Overflow Blog
Engineering at Meta
Engineering at Meta
云风的 BLOG
云风的 BLOG
Last Week in AI
Last Week in AI
C
Cyber Attacks, Cyber Crime and Cyber Security
Webroot Blog
Webroot Blog
C
Check Point Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
W
WeLiveSecurity
T
Threat Research - Cisco Blogs
人人都是产品经理
人人都是产品经理
Hacker News: Ask HN
Hacker News: Ask HN
The Hacker News
The Hacker News
V
Vulnerabilities – Threatpost
Microsoft Security Blog
Microsoft Security Blog

Arpit Bhayani

Temporal Primer - Building Long-Running Systems What Matters in Production RAG Structure of Every LLM Chat How LLMs Really Work Your Monolith Is Already A Distributed System Databases Were Not Designed For This BM25 JOIN Algorithms Venting at Work Comes at a Reputation Cost Why Half Your Skills Expire Every Few Years Multi-Paxos - Consensus in Distributed Databases MySQL Replication Internals Bloom Filters When You Increase Kafka Partitions Product Quantization The Q, K, V Matrices The Day I Accidentally Deleted Production How LLM Inference Works What are Blocking Queues and Why We Need Them Heartbeats in Distributed Systems How Writes Work in Apache Cassandra Redis Replication Internals How to Handle Arrogant Colleagues at Work How Does a CDN Handle Content Replication You Can't Fix Everything on Day One When Emotions Spill Over at Work Why gRPC Uses HTTP2 Meetings With No Agenda Are a Waste of Time Career Longevity Beats Constant Job Hopping Stay Relevant at Higher Salary Levels Why Distributed Systems Need Consensus Algorithms Like Raft Why Do Databases Deadlock and How Do They Resolve It Why and How Cache Locality Can Make Your Code Faster Why Eventual Consistency is Preferred in Distributed Systems Why does DNS use both UDP and TCP Should You Do a Master's My Honest Take Empathy Makes Great Engineers Unstoppable Good Mentors Build People, Not Just Skills Why You Should Always Have Back-Burner Projects Before You Push Back, Know What You're Standing On Be the One They Can Count On How Much Are People Willing to Bet on You How to Get Leadership to Say Yes to Your Project Don't Let Your Best Ideas Die in Silence Be the Person Everyone Wants to Work With The XY Problem and How to Avoid It The Startup Hiring Lie Nobody Talks About You Won't Be Promoted Unless You Ask It's Not Enough to be Right; Learn to be Heard No One Ships Great Software Alone You Don't Win by Proving Others Wrong Appreciate Generously; It Costs Nothing, But Builds Everything Your Soft Skills Aren't Soft at All Before you form an opinion, experience it Why You Need Both Curiosity and Action to Thrive A Daily Worklog Changed Everything How We Handle Mistakes Defines Us Own Your Mistakes Don't Wait. Step Up. Temporary Fixes Are Permanent Why Interviews Are Biased And What Sets You Apart Saying 'This isn't my problem' is actually the problem How to Write Effective OKRs Never Lose a Battle due to Miscommunication When In Doubt, Code It Out How to Follow Up Without Annoying People Lead Projects That Land, Execution Over Everything Abstract Thinking Will Define Your Next Decade We Engineers Suck at Task Estimation Shiny Obect Syndrome in Tech When to Change Jobs - The 3P Framework Comfort and Competition - Know When to Switch Gears Paper Notes - On-demand Container Loading in AWS Lambda Paper Notes - SQL Has Problems. We Can Fix Them Pipe Syntax In SQL Paper Notes - NanoLog - A Nanosecond Scale Logging System Don't Wait, Learn - The Best Resource is Mythical Paper Notes - WTF - The Who to Follow Service at Twitter The Unexpected Benefit of Reading Random Engineering Articles Roadmaps Are Limiting Your Growth Stop Leaving Money on the Table - Negotiate Your Job Offer Never Bad-Mouth Your Past Employers Show You're a Culture Fit Quantify your resume, Know Your Numbers The Importance of Being Likeable in Interviews Questions to Ask Your Interviewer How to Build Trust Through Collaboration Do This, Once You Are Out of the Interview Cycle Stop Pitching Ideas, Start Pitching Projects Read Those Design Docs, Even the Ones That Seem Irrelevant The Best Engineering Lessons Happen During Outages Great Engineers Start Broad LLM Summaries are Ruining Your Learning Turn System Design Interviews into Discussions Title Inflation At Work, Find Your Own Projects 6 Simple Strategies to Cracking Any Tech Interview How to Remain Unblocked Solving the Knapsack Problem with Evolutionary Algorithms Generating Pseudorandom Numbers with LFSR Local vs Global Indexes in Partitioned Databases
Visualizing Recursion in Python with Just a Decorator
Arpit Bhayani · 2020-12-13 · via Arpit Bhayani

One programming paradigm, that is hardest to visualize, as almost every single programmer out there will agree on, is Recursion. We usually use pen and paper to visualize the flow and check how recursion is behaving. But what if, this could be done programmatically, and today we address this very problem and try to come up with a simple yet effective solution.

This essay is going to be a little different from the usuals; instead of taking a look into a research paper or an algorithm, we will implement a simple and easy recursion visualizer for Python.

Recursion Tree

Recursion helps in solving a larger problem by breaking it into smaller similar ones. The classic implementation of recursion in the world of programming is when a function invokes itself using reduced parameters while having a base terminating condition.

def fib(n):
  # base condition mimicking the first two numbers
  # in the sequence
  if n == 0: return 0
  if n == 1: return 1

  # every number is summation of the previous two
  return fib(n - 1) + fib(n - 2)

The most common problem that is solved using recursion is computing the nth Fibonacci Number. A trivial recursive Python function that spits out nth Fibonacci Number is as shown below

The most effective way of visualizing recursion is by drawing a recursion tree. It is very useful for visualizing what happens when a recurrence is iterated. The recursion tree for the above function fib for input n = 3 is as illustrated below

https://user-images.githubusercontent.com/4745789/102004754-74fb7980-3d39-11eb-991e-0f54fa7f20c6.png

Decorating to visualize

Instead of printing an actual tree-like recursion tree, we take some liberty and print a close-enough version of it running top-down. To keep track of recursive function calls we use Python Decorators that essentially wraps the function allowing us to invoke statements before and after the function call.

The decorator that wraps the recursive function and prints the recursion tree is as illustrated below.

def recviz(fn):
    """Decorator that pretty prints the recursion tree with
       args, kwargs, and return values.
    """

    # holds the current recursion level
    recursion_level = 1

    def wrapper(*args, **kwargs):

        # we register a nonlocal recursion_level so that
        # it binds with the recursion_level variable.
        # in this case, it will bind to the one defined
        # in recviz function.
        nonlocal recursion_level

        # Generate the pretty printed function string
        fn_str = pretty_func(fn, args, kwargs)

        # Generate the whitespaces as per the recursion level
        whitespace = "   " * (recursion_level - 1)

        # Pretty print the function with the whitespace
        print(f"{whitespace} -> {fn_str}")

        # increment the recursion level
        recursion_level += 1

        # Invoke the wrapped function and hold the return value
        return_value = fn(*args, **kwargs)

        # Post function evaluation we decrease the recursion
        # level by 1
        recursion_level -= 1

        # Pretty print the return value
        print(f"{whitespace} <- {repr(return_value)}")

        # Return the return value of the wrapped function
        return return_value

    return wrapper

We use recursion_level to keep track of the current recursion level using which we decide the indentation. The value of this variable is increased every time we are about the invoke the function while it is reduced post the execution. In order to pretty-print the invoked function, we have a helper method called pretty_func whose implementation can be found here.

When we decorate our previously defined fib function and invoke it with n = 3 we get the following output.

 -> fib(3)
    -> fib(2)
       -> fib(1)
       <- 1
       -> fib(0)
       <- 1
    <- 2
    -> fib(1)
    <- 1
 <- 3

The above output renders how recurrence is evaluated and is pretty printed to make it more human-readable. The right arrow -> defines a function invocation while the left arrow <- indicates the return value post invocation.

Publishing it on PyPI

Everything mentioned above is published in a Python Package and hosted on PyPI at pypi/recviz. So in order to use this, simply install the package recviz like a usual Python package using pip and decorate the recursive function.

from recviz import recviz

@recviz
def fib(n):
  # base condition mimicking the first two numbers
  # in the sequence
  if n == 0: return 0
  if n == 1: return 1

  # every number is summation of the previous two
  return fib(n - 1) + fib(n - 2)

fib(3)

References