Recursion & Lambda
def fact(n):
if n == 1:
return 1
return n * fact(n - 1)
print(fact(3))fact(3) needs fact(2) first, so it waits.
1Level 1 · BasicsBasics
This lesson covers two ideas about functions. Recursion is a function that calls itself to solve smaller versions of a problem. Lambda functions are tiny one-line functions without a name, handy for sorting and filtering.
Recursion: solving a problem with a smaller copy of itself
Think of Russian nesting dolls: to find the smallest doll, open the doll, then do the same thing with the doll inside, until there's nothing left to open. Factorial works the same way: 5! = 5 × 4!, and 4! = 4 × 3!, and so on, down to 1! = 1.
def factorial(n):
if n <= 1: # base case: stop here
return 1
return n * factorial(n - 1) # recursive case
Every recursive function needs two parts:
- A base case that answers directly without recursing. Without it the function calls itself forever and Python stops it with a
RecursionError. - A recursive case that moves closer to the base case, for example
n - 1.
Recursion shines for naturally nested problems: folders inside folders, family trees, and splitting a problem in half (like binary search). For simple counting, a loop is usually faster and clearer.
Lambda: a function in one line
square = lambda x: x * x square(5) # 25
A lambda takes parameters before the colon and returns the expression after it. It's the same as def square(x): return x * x. You'll mostly use lambdas as arguments to other functions:
sorted(students, key=lambda s: s["cgpa"]) # sort by cgpa max(words, key=len) # longest word list(filter(lambda n: n > 0, nums)) # keep positives list(map(lambda n: n * 2, nums)) # double each
The key function tells sorted, max and min what to compare. Add reverse=True to sort from high to low.
Key points: a recursive function calls itself and must have a base case; each call should move towards the base case;lambda x: expris a small anonymous function; pass it askey=to sort or find max/min by any rule.
See it in actionRecursion stacks up, then unwinds
Each call to fact() adds a frame on top. Watch them return one by one.
Try it yourselfExample 1: Factorial with recursion
Each call waits for the smaller call to finish. Try factorial(10).
Output appears hereFactorial
Fill the blanks so the recursive function prints 120 (5! = 5 × 4 × 3 × 2 × 1).
def fact(n): if n == : return 1 return n * fact(n 1) print(fact(5))
Example 2: Watching recursion happen
The indentation shows each call going deeper, then returning.
Output appears hereExample 3: Sum of digits, recursively
The last digit plus the digit sum of the rest. The base case is a single digit.
Output appears hereNever-ending recursion
This should count down 3 2 1 on separate lines, but it never stops. Add the missing base case.
Power, recursively
Write a recursive function power(b, e) that returns b to the power e without using ** or pow. Print power(2, 10), which is 1024.
Example 4: Sorting with lambda
The key function picks what to compare.
Output appears hereSort by length
Fill the blanks so the words are sorted from shortest to longest: ['ox', 'cat', 'horse'].
words = ["horse", "ox", "cat"] print(sorted(words, key= w: (w)))
Example 5: map and filter
map() applies a function to every item; filter() keeps items where it returns True.
Output appears hereDouble with map
Use map with a lambda to double every number in [3, 5, 8] and print [6, 10, 16].
2Level 2 · IntermediateRecursion on lists and strings, lambdas as keys
Every recursion needs two parts
A base case that answers directly, and a recursive case that makes the problem smaller. Forget the base case and Python stops you with RecursionError after about 1000 calls.
Recursing on sequences
"The sum of a list is its first item plus the sum of the rest." Many list and string problems can be phrased this way: reverse, count, check palindromes, flatten nested lists.
Lambdas with sorted, max and min
max(students, key=lambda s: s["gpa"]) finds the best student. Sorting by several things: key=lambda s: (-s["gpa"], s["name"]).
See it in actionFlattening nested lists recursively
Watch the call stack grow for each inner list, then shrink as results come back.
Example 6: Recursion on strings
Each function shrinks the string by one character until it's empty.
Output appears hereExample 7: Lambdas as sort keys
Highest GPA first; ties go alphabetically by name.
Output appears here3Level 3 · AdvancedMemoization, backtracking and functional tools
Memoization
Naive fib(35) makes about 30 million calls because it solves the same small problems again and again. Remembering each answer in a dictionary (a memo) cuts that to under 100. (In the Decorators lesson, @functools.lru_cache does the remembering for you.) This idea is the heart of dynamic programming.
Backtracking
To list all arrangements or subsets, choose an option, recurse, then undo the choice and try the next. Puzzles like N-Queens and Sudoku use this.
Recursion depth
Python's default limit is about 1000 nested calls. For deep problems, convert to a loop with your own stack.
Functions that make functions
A function can return a lambda that remembers the outer function's arguments: make_tax(0.15) gives back a ready-made VAT function. Pair it with map() and filter(). (The functools module, in the next lesson, adds reduce and partial.)
See it in actionBacktracking builds every subset
Watch chosen grow and shrink as the function tries "take it" and then "leave it".
Example 8: Memoization makes recursion fast
The counter shows how many calls each version makes.
Output appears hereExample 9: map, filter and a function that makes functions
make_tax() returns a new function that remembers its rate. Try making a 5% tax too.
Output appears heref(n + 1) when the base case is n == 0), ends with RecursionError: maximum recursion depth exceeded.What does this print?
def f(n):
if n == 0:
return 0
return n + f(n - 1)
print(f(4))50 graded problems are waiting in Topic Practice.