Recursion

Functions calling themselves

Interview Relevant: Very common in interviews

Recursion

Functions that call themselves.

Code Examples

Recursive functions and optimization.

python
1# Factorial
2def factorial(n):
3    if n <= 1:       # Base case
4        return 1
5    return n * factorial(n - 1)  # Recursive case
6
7# Fibonacci
8def fib(n):
9    if n <= 1:
10        return n
11    return fib(n-1) + fib(n-2)
12
13# With memoization
14from functools import lru_cache
15
16@lru_cache(maxsize=None)
17def fib_memo(n):
18    if n <= 1:
19        return n
20    return fib_memo(n-1) + fib_memo(n-2)
21
22# Recursion limit
23import sys
24sys.setrecursionlimit(10000)  # Default ~1000

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In