Recursion on strings and lists
Write recursive functions on strings and lists that handle the first item and recurse on the rest, with the empty string or list as the base case.
It opens on
To reverse "stop", suppose someone hands you "top" already reversed, as "pot". What do you do with the "s"?
Why it matters
Splitting a sequence into its first item and the rest is the pattern behind recursive code on lists, strings, files and trees, and writing reverse, sum or count this way is a standard exam question in a first programming course.
Good to know first
- Recursion: base case and recursive case: a smaller call and a case that stops
- Indexing and slicing: s[0] is the first item and s[1:] the rest
- Lists: indexing and mutation: xs[0] and len
Step by step
First and rest of a string
Write reverse(s) recursively from s[0] and s[1:], and trace its calls down to the empty string.
That answers the opening question; put the first letter after the reversed rest. In Python, reverse(s) returns reverse(s[1:]) + s[0].
recursive reverse
A common mix-up
Reverse(s[1:]) + s[0] puts the first letter first.
In fact: It adds s[0] after the reversed rest, so it ends up last.
Sum and count a list
Write total and count on a list by the first item and the rest, with the empty list as the base case.
total([4, 7, 1, 8]) is 4 + total([7, 1, 8]), and so on down to total([]), which is 0. Coming back up, total([8]) returns 8.
the calls of total
A common mix-up
The base case of total should be a list of one item.
In fact: The empty list is simpler and safer, since total([]) is 0 and a one-item base case fails on an empty list.
Choosing the base case
Choose a base case that every input reaches, and spot a function that fails on the empty string or a long list.
An empty string's [1:] is still the empty string, so the call never gets smaller. The empty string is a real input, an empty line in a file, so the base case must cover it. Using s == "" covers every string.
A common mix-up
If a recursive function works on a few test strings it works on all of them.
In fact: It may still fail on the empty string or on a very long input; test the smallest and largest cases.
Try it
Trace reverse("dog") and give each returned value.Answer
The empty string, "g", "go", "god"
Hint: Reverse("og") is "go"
Write length(xs) recursively, and give length([9, 9, 9]).Answer
If xs == [] return 0; otherwise return 1 + length(xs[1:]); 3
Hint: Each item adds 1
A classmate writes total with the base case len(xs) == 1, returning xs[0]. Which input breaks it, and what happens?Answer
The empty list; len 0 is never 1 and [][1:] is [], so it raises RecursionError
Hint: What is [][1:]?
If "top" reversed is "pot", where does the "s" go to make "stop" reversed?Answer
At the end, giving "pots".
What is the total of an empty list, and why is that the right base case?Answer
0, since adding 0 to the last item gives it unchanged, and every list shrinks to the empty list.
