Coding Towards The Answer, Part 6

Tracing Recursion And Iteration …

Mi'kail Eli'yah
8 min readJun 26, 2023

Many times, we get lost in the call of things. Let’s put a probe tracer to know how it does down (and up) the stack.

# Global variable to track the depth
depth = 0

def recursive_function(target_depth):
global depth

# Print the depth
print("Depth:", depth)

# Base case
if depth >= target_depth:
return

# Recursive call
depth += 1
recursive_function(target_depth)
# depth -= 1

# Call the recursive function
target_depth = 8
recursive_function(target_depth)

print("Depth (reported in main):", depth)

"""
Depth: 0
Depth: 1
Depth: 2
Depth: 3
Depth: 4
Depth: 5
Depth: 6
Depth: 7
Depth: 8

Depth (reported in main): 8
"""
In recursion as stacks are used, the variable depth changes within each call as it pushes or pops (recalls) variable within the context of the call. 

In iteration when we link one object within another:

class Node:
def __init__(self, value, depth=0):
self.value = value
self.depth = depth
self.children = []

def add_child(self, value):
child = Node(value, self.depth + 1)
self.children.append(child)
return child

def…

--

--

Mi'kail Eli'yah
Mi'kail Eli'yah

No responses yet