DSA 27: Anagram - Call Stack

An introductory look at the call stack of the anagram recursive function
data structures
algorithms
Author

Tony Phung

Published

February 10, 2025

1. Install showcallstack

  • pip install showcallstack or
  • uv add showcallstack (if using uv)

2. Save anagrams function to a .py (python script)

# dsa-anagram-call-stack.py
import showcallstack as ss

def anagrams(string):
    # ss.showcallstack()
    if len(string)==1:
        return string[0]
    collection = []
    substr_anagrams = anagrams(string[1:])
    for anagram in substr_anagrams:
        ss.showcallstack()
        for i in range(len(anagram)+1):
            new_string = anagram[:i]+string[0]+anagram[i:]
            collection.append(new_string)
    return collection

anagrams("abc")

3. Run .py script from terminal

  • uv run dsa-anagram-call-stack.py

4. showcallstack(): High-Level

This function shows information about callstack.

Note:

  • The local variables to the showcallstack() depends where the function call is placed

5. showcallstack(): Low-Level

Placing the function call inside the for loop shows the a greater granularity of local variables of each call in the call stack.

# dsa-anagram-call-stack2.py
import showcallstack as ss

def anagrams(string):
    # ss.showcallstack()
    if len(string)==1:
        return string[0]
    collection = []
    substr_anagrams = anagrams(string[1:])
    for anagram in substr_anagrams:
        ss.showcallstack()
        for i in range(len(anagram)+1):
            new_string = anagram[:i]+string[0]+anagram[i:]
            collection.append(new_string)
    return collection

anagrams("abc")

Note:

  • The iteration of i below