1. Define Recursive Generator recurse(n)
def recurse(n):
if n > 0:
yield n
yield from recurse(n - 1)
What it does:
It's a recursive generator function.
It takes a number n.
If n > 0, it does the following:
yield n – yields the current value of n.
yield from recurse(n - 1) – recursively calls itself with n - 1 and yields all values from that call.
2. Call and Convert to List
print(list(recurse(3)))
This line:
Calls recurse(3), which returns a generator.
Converts all values from that generator into a list.
Step-by-Step Execution
Let’s trace the recursion:
recurse(3):
Yields 3
Calls recurse(2)
recurse(2):
Yields 2
Calls recurse(1)
recurse(1):
Yields 1
Calls recurse(0)
recurse(0):
Base case: n is not greater than 0, so it yields nothing.
The Yields Accumulate as:
3 → 2 → 1
Final Output
[3, 2, 1]
.png)

0 Comments:
Post a Comment