06 Recursion, Generator Flashcards
What is a recursive function?
It’s a function that calls itself.
What does a recursive function need to avoid running into an endless loop?
a base case or recursion anchor
What is a base case or recursive anchor?
It’s a state in a recursive function where, after splitting the task into subtask and rest, the rest can be solved immediately.
What’s the general idea of how to “solve” a recursive function?
Split the task into smaller subtask and a rest, call itself and again split the task/rest into a smaller subtask and rest. Repeat until the rest can be solved immediately without having to split it first.
What happens if a recursive function doesn’t have a base case or recursive anchor?
It runs into an endless loop.
True or False: There can only be one base case per recursive function.
False. A recursive function can have multiple base cases.
True or False: There can be multiple recursive calls in a function.
True
Apart from running into an endless loop, what other error can occur with recursion?
Stack overflow, if the recursion depth is too high.
What is a recursion depth?
The amount of times the function calls itself.
What is the default recursion depth in Python and how can it be changed?
default: 1000
can be changed: sys.setrecursionlimit(x)
What is a Generator Function?
It’s a function, that uses the keyword “yield” instead of “return”. It returns a generator iterator object.
After reaching the “yield” keyword the specified value is returned and the execution of the function is paused. Only if the function is called again does it resume again.
What is the advantage of a generator function over a normal function?
It also yields a result when needed instead of processing everything instantly. That saves memory.