Module 6 · Recursion, Backtracking and Divide and Conquer · Lesson 20 of 40
Recursion on lists and strings
Practise the shrink-and-combine habit on lists and words, and compare recursion with loops.
In this lesson · about 20 minutes
- Write recursive functions on strings and lists
- Use two indexes instead of slicing to save work
- Decide when a loop is simpler
Strings and lists shrink nicely: take one item off, recurse on the rest.
Reverse a string
def rev(s):
if s == "":
return ""
return rev(s[1:]) + s[0] # reverse the rest, then add the first letter at the end
Palindrome with two indexes
Slicing (s[1:]) copies the string every call. Passing indexes instead avoids the copying:
def is_pal(s, left, right):
if left >= right:
return True
if s[left] != s[right]:
return False
return is_pal(s, left + 1, right - 1)
Binary search, the recursive way
Binary search is naturally recursive: search the left half or the right half, which is a smaller copy of the same problem.
Recursion or loop?
| Recursion | Loop |
|---|---|
| Clear for problems that branch (trees, all combinations) | Clear for simple "go through each item" |
| Uses call-stack memory: O(depth) | Usually O(1) extra memory |
| Python stops at about 1,000 waiting calls | No depth limit |
Any recursion can be written as a loop (sometimes with your own stack), and the other way round. Choose whichever is easier to read.
Try it: recursive tools
Exercise
Biggest number, recursively
Write a recursive rec_max(nums) for a non-empty list: the biggest of the list is the bigger of the first item and the biggest of the rest. Base case: a list with one item.
Exercise
Palindrome with indexes
Finish the recursive is_pal(s, left, right) from the lesson.
Check your understanding0 of 2 correct
Quiz score: 0 of 2
Exercises solved: 0 of 2
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.