u06_slides-flashcards
Front
Back
What is a recursive function?
A function that calls itself, either directly or indirectly (via other function calls)
What are the key components of a recursive function?
- Base case (recursion anchor) that ends the recursion
- Recursive case that breaks the problem into smaller subtasks
What is a base case in recursion?
A condition where the function can solve the problem immediately without making additional recursive calls, preventing infinite recursion
When should you use recursion instead of iteration?
Use recursion when it’s the most natural way to solve a problem, especially for:
1. Traversing tree-like data structures
2. Processing nested data structures
3. Problems using ‘divide and conquer’ principle
What are the drawbacks of recursion?
- Can be less efficient than iteration due to function call overhead
- Risk of stack overflow with high recursion depth
- Default recursion depth limit in Python is 1000
How can you increase Python’s recursion limit?
Using sys.setrecursionlimit(…)
What is a generator function?
A function that uses ‘yield’ instead of ‘return’ to return a generator iterator object, executing code only when elements are requested
How is a generator function’s execution different from regular functions?
Generator functions suspend execution after reaching a yield statement and resume when the next element is requested, rather than processing everything at once
What is the advantage of using generator functions?
They generate elements on-demand rather than processing everything at once, which can save memory
How do you access elements from a generator?
- Using a for loop to iterate through elements
- Using the built-in next() function
What happens when you call next() on a generator that has no more elements?
It raises a StopIteration exception
Can generator functions create infinite sequences?
Yes, they can create infinite sequences since they only generate values when requested, making them memory-efficient
What happens when you create a generator object without requesting elements?
The generator function’s code is not executed until elements are actually requested (lazy evaluation)
What’s an example of a simple generator function?
def generate_str_numbers(n):
for i in range(n):
yield str(i)