Book 4 · Chapter P4.7
Recursion
B4·7This chapter is in the ebook.
Read it in full on cswithzak.com. Every question has its mark scheme and every program is ready to run. The free practice for each section is below, with the short code the book prints beside it.
For the whole chapter
- Topic pageComputational Thinking and Problem-Solving
B4·7·T - QuizComputational Thinking & Problem-Solving
B4·7·Q1 - LabAlgorithm Lab (sorts, binary search, recursion)
B4·7·X1 - LabData Structures Playground
B4·7·X2 - LabProgramming tasks (stacks, queues, recursion)
B4·7·X3
§19.2 Recursion
Short code B4·7·1
- FlashcardsFlashcards §19.2: Recursion
B4·7·F1 - Past-paper questionsPast-paper questions §19.2 (recursion)
B4·7·1
Recursion, from pseudocode to code
Short code B4·7·10
def OpenDoll(Size):
if Size == 1:
print("Size 1: the smallest doll")
else:
print("Open doll", Size)
OpenDoll(Size - 1)
print("Close doll", Size)
OpenDoll(3)Close lines wait until the smallest doll (the base case) has been reached, then run in reverse order.Output
Open doll 3 Open doll 2 Size 1: the smallest doll Close doll 2 Close doll 3
Part A: recursive functions, factorial
Short code B4·7·11
def Factorial(N):
if N <= 1: # base case
return 1
else: # general case
return N * Factorial(N - 1)
for Number in range(0, 6):
print(Number, Factorial(Number))
print(12, Factorial(12))N <= 1) returns 1 without a call; the general case returns N times the factorial of N - 1. 0! is 1, so the base case also stops Factorial(0).Output
0 1 1 1 2 2 3 6 4 24 5 120 12 479001600
def Factorial(N):
if N == 1:
return 1
else:
return N * Factorial(N - 1)
print(Factorial(5))
try:
print(Factorial(0))
except RecursionError as Error:
print("RecursionError:", Error)N == 1, Factorial(0) calls Factorial(-1), Factorial(-2)… and never reaches 1. Python stops it at its recursion limit.Output
120 RecursionError: maximum recursion depth exceeded
Functions that shrink a number
Short code B4·7·12
def SumDigits(N):
if N < 10:
return N
else:
return N % 10 + SumDigits(N // 10)
def Power(Base, Exponent):
if Exponent == 0:
return 1
else:
return Base * Power(Base, Exponent - 1)
print(SumDigits(4072), SumDigits(9))
print(Power(2, 10), Power(3, 4), Power(7, 0))SumDigits peels off the last digit with MOD and recurses on the rest with DIV; Power lowers the exponent by 1 until it is 0.Output
13 9 1024 81 1
def CountDigits(N):
if N < 10:
return 1
else:
return 1 + CountDigits(N // 10)
print(CountDigits(7), CountDigits(4072), CountDigits(100000))CountDigits Mark Ladder's model answer, called three times.Output
1 4 6
Module Program
Function Product(A As Integer, B As Integer) As Integer
If B = 0 Then
Return 0
Else
Return A + Product(A, B - 1)
End If
End Function
Sub Main()
Console.WriteLine(Product(6, 4) & " " & Product(9, 0) & " " & Product(0, 5))
End Sub
End ModuleProduct by repeated addition).Output
24 0 0
Recursion on strings: reverse and palindrome
Short code B4·7·13
def Reverse(Text):
if len(Text) <= 1:
return Text
else:
return Reverse(Text[1:]) + Text[0]
def IsPalindrome(Text):
if len(Text) <= 1:
return True
elif Text[0] != Text[-1]:
return False
else:
return IsPalindrome(Text[1:-1])
print(Reverse("stressed"))
for Word in ["level", "noon", "robot", "a"]:
if IsPalindrome(Word):
print(Word, "is a palindrome")
else:
print(Word, "is not a palindrome")Reverse puts the first character after the reversed rest; IsPalindrome compares the two ends and recurses on the middle. A string of 0 or 1 characters is the base case of both.Output
desserts level is a palindrome noon is a palindrome robot is not a palindrome a is a palindrome
def IsPalindrome(Text):
if len(Text) <= 1:
return False # wrong: a 0- or 1-character string IS a palindrome
elif Text[0] != Text[-1]:
return False
else:
return IsPalindrome(Text[1:-1])
print(IsPalindrome("level"), IsPalindrome("noon"), IsPalindrome("robot"))IsPalindrome with the base case returning False. Every chain of calls ends at the base case, so every word comes out False, palindromes included.Output
False False False
Counting with recursion
Short code B4·7·14
def CountChar(Text, Letter):
if len(Text) == 0:
return 0
elif Text[0] == Letter:
return 1 + CountChar(Text[1:], Letter)
else:
return CountChar(Text[1:], Letter)
def CountAbove(Values, N, Limit):
# counts the elements among the first N of Values that are above Limit
if N == 0:
return 0
elif Values[N - 1] > Limit:
return 1 + CountAbove(Values, N - 1, Limit)
else:
return CountAbove(Values, N - 1, Limit)
print(CountChar("banana", "a"))
Marks = [45, 72, 38, 90, 61, 55]
print(CountAbove(Marks, 6, 50), CountAbove(Marks, 3, 50))CountChar looks at the first character and recurses on the rest; CountAbove looks at element N - 1 and recurses on the first N - 1 elements. Each adds 1 to the count the recursive call returns.Output
3 4 1
def CountChar(Text, Letter):
if len(Text) == 0:
return 0
elif Text[0] == Letter:
return 1 + CountChar(Text[1:], Letter)
else:
CountChar(Text[1:], Letter) # the value is lost
print(CountChar("b", "a"))
try:
print(CountChar("ab", "a"))
except TypeError as Error:
print("TypeError:", Error)return, so Python hands back None, and the 1 + above it then fails.Output
None TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
Fibonacci: two calls at once
Short code B4·7·15
Calls = 0 # global INTEGER: counts every call of Fib
def Fib(N):
global Calls
Calls = Calls + 1
if N <= 2:
return 1
else:
return Fib(N - 1) + Fib(N - 2)
Line = ""
for N in range(1, 11):
Line = Line + str(Fib(N)) + " "
print(Line)
for N in [5, 10, 20]:
Calls = 0
Answer = Fib(N)
print("Fib(" + str(N) + ") =", Answer, "after", Calls, "calls")Fib(20) needs 13 529 calls.Output
1 1 2 3 5 8 13 21 34 55 Fib(5) = 5 after 9 calls Fib(10) = 55 after 109 calls Fib(20) = 6765 after 13529 calls
Tracing calls with indentation
Short code B4·7·16
def Factorial(N, Depth):
print(" " * Depth + "Factorial(" + str(N) + ") called")
if N <= 1:
Result = 1
else:
Result = N * Factorial(N - 1, Depth + 1)
print(" " * Depth + "Factorial(" + str(N) + ") returns " + str(Result))
return Result
print("Answer:", Factorial(4, 0))Depth grows by 1 with each call, so each call's lines are indented one step further. The called lines are the winding; the returns lines, in reverse order, are the unwinding.Output
Factorial(4) called
Factorial(3) called
Factorial(2) called
Factorial(1) called
Factorial(1) returns 1
Factorial(2) returns 2
Factorial(3) returns 6
Factorial(4) returns 24
Answer: 24def Power(Base, Exponent, Depth):
print(" " * Depth + "Power(" + str(Base) + ", " + str(Exponent) + ")")
if Exponent == 0:
Result = 1
else:
Result = Base * Power(Base, Exponent - 1, Depth + 1)
print(" " * Depth + "returns " + str(Result))
return Result
print(Power(2, 3, 0))Power Mark Ladder's model answer: Power(2, 3, 0).Output
Power(2, 3)
Power(2, 2)
Power(2, 1)
Power(2, 0)
returns 1
returns 2
returns 4
returns 8
8public class Main {
static int SumDigits(int N, int Depth) {
System.out.println(" ".repeat(Depth) + "SumDigits(" + N + ")");
int Result;
if (N < 10) {
Result = N;
} else {
Result = N % 10 + SumDigits(N / 10, Depth + 1);
}
System.out.println(" ".repeat(Depth) + "returns " + Result);
return Result;
}
public static void main(String[] args) {
System.out.println(SumDigits(482, 0));
}
}SumDigits(482, 0).Output
SumDigits(482)
SumDigits(48)
SumDigits(4)
returns 4
returns 12
returns 14
14Part B: recursive binary search
Short code B4·7·17
def BinarySearch(Values, Low, High, Target):
if Low > High:
return -1 # base case: not found
Mid = (Low + High) // 2
if Values[Mid] == Target:
return Mid # base case: found
elif Values[Mid] < Target:
return BinarySearch(Values, Mid + 1, High, Target)
else:
return BinarySearch(Values, Low, Mid - 1, Target)
Codes = [11, 17, 23, 30, 38, 46, 52, 64, 79, 85]
print(BinarySearch(Codes, 0, 9, 64))
print(BinarySearch(Codes, 0, 9, 11))
print(BinarySearch(Codes, 0, 9, 40))Output
7 0 -1
Output
Low 0 High 9 Mid 4 Values[Mid] 38 Low 5 High 9 Mid 7 Values[Mid] 64 Result 7 Low 0 High 9 Mid 4 Values[Mid] 38 Low 5 High 9 Mid 7 Values[Mid] 64 Low 5 High 6 Mid 5 Values[Mid] 46 Low 5 High 4 -> not found Result -1
Recursion on a tree
Short code B4·7·18
# Each row of Tree is [LeftPointer, Data, RightPointer]; -1 is a null pointer
Tree = [[1, 41, 2], [5, 23, 3], [4, 67, 6],
[-1, 30, -1], [-1, 52, 7], [-1, 15, -1],
[-1, 88, -1], [-1, 60, -1]]
Root = 0
def InOrder(Index):
if Index != -1:
InOrder(Tree[Index][0])
print(Tree[Index][1], end=" ")
InOrder(Tree[Index][2])
def PreOrder(Index):
if Index != -1:
print(Tree[Index][1], end=" ")
PreOrder(Tree[Index][0])
PreOrder(Tree[Index][2])
def PostOrder(Index):
if Index != -1:
PostOrder(Tree[Index][0])
PostOrder(Tree[Index][2])
print(Tree[Index][1], end=" ")
InOrder(Root)
print()
PreOrder(Root)
print()
PostOrder(Root)
print()Output
15 23 30 41 52 60 67 88 41 23 15 30 67 52 60 88 15 30 23 60 52 88 67 41
Tree = [[1, 41, 2], [5, 23, 3], [4, 67, 6], [-1, 30, -1],
[-1, 52, 7], [-1, 15, -1], [-1, 88, -1], [-1, 60, -1]]
Root = 0
def Find(Index, Target):
if Index == -1:
return -1 # fell off the tree
elif Tree[Index][1] == Target:
return Index
elif Target < Tree[Index][1]:
return Find(Tree[Index][0], Target)
else:
return Find(Tree[Index][2], Target)
def CountNodes(Index):
if Index == -1:
return 0
else:
return 1 + CountNodes(Tree[Index][0]) + CountNodes(Tree[Index][2])
print(Find(Root, 60), Find(Root, 30), Find(Root, 50))
print(CountNodes(Root), CountNodes(2))Find follows one branch (it compares and goes left or right), CountNodes visits both branches and adds.Output
7 3 -1 8 4
Part C: from recursion to iteration
Short code B4·7·19
def SumDigits(N):
Total = 0
while N >= 10: # the general case runs while N has 2+ digits
Total = Total + N % 10
N = N // 10
return Total + N # the base case: one digit left
def BinarySearch(Values, Target):
Low = 0
High = len(Values) - 1
while Low <= High: # base case "Low > High" becomes the stop
Mid = (Low + High) // 2
if Values[Mid] == Target:
return Mid
elif Values[Mid] < Target:
Low = Mid + 1 # was: a call with Mid + 1, High
else:
High = Mid - 1 # was: a call with Low, Mid - 1
return -1
Codes = [11, 17, 23, 30, 38, 46, 52, 64, 79, 85]
print(SumDigits(4072), SumDigits(9))
print(BinarySearch(Codes, 64), BinarySearch(Codes, 11), BinarySearch(Codes, 40))Output
13 9 7 0 -1
def CountChar(Text, Letter):
Count = 0
for Index in range(len(Text)):
if Text[Index] == Letter:
Count = Count + 1
return Count
print(CountChar("banana", "a"), CountChar("", "a"))CountChar Mark Ladder's model answer.Output
3 0
public class Main {
static int CountDigits(int N) {
int Count = 1;
while (N >= 10) {
N = N / 10;
Count = Count + 1;
}
return Count;
}
public static void main(String[] args) {
System.out.println(CountDigits(7) + " " + CountDigits(4072) + " " + CountDigits(100000));
}
}CountDigits.Output
1 4 6
From iteration to recursion
Short code B4·7·20
def IterativeUpper(Text):
Count = 0
for Index in range(len(Text)):
if Text[Index] >= "A" and Text[Index] <= "Z":
Count = Count + 1
return Count
def RecursiveUpper(Text):
if len(Text) == 0: # the loop has run out of characters
return 0
elif Text[0] >= "A" and Text[0] <= "Z": # the loop body, on the first character
return 1 + RecursiveUpper(Text[1:])
else:
return RecursiveUpper(Text[1:])
for Phrase in ["Paper Four", "CS with ZAK", "abc"]:
print(IterativeUpper(Phrase), RecursiveUpper(Phrase))Output
2 2 5 5 0 0
def SumEven(Values, Size):
Total = 0
for Index in range(Size):
if Values[Index] % 2 == 0:
Total = Total + Values[Index]
return Total
def RecursiveSumEven(Values, N):
if N == 0:
return 0
elif Values[N - 1] % 2 == 0:
return Values[N - 1] + RecursiveSumEven(Values, N - 1)
else:
return RecursiveSumEven(Values, N - 1)
Data = [7, 4, 10, 3, 8]
print(SumEven(Data, 5), RecursiveSumEven(Data, 5), RecursiveSumEven(Data, 2))SumEven Mark Ladder: the given iterative function and the recursive model answer agree.Output
22 22 4
Module Program
Function CountSpaces(Text As String) As Integer
If Len(Text) = 0 Then
Return 0
ElseIf Mid(Text, 1, 1) = " " Then
Return 1 + CountSpaces(Mid(Text, 2))
Else
Return CountSpaces(Mid(Text, 2))
End If
End Function
Sub Main()
Console.WriteLine(CountSpaces("CS with ZAK") & " " & CountSpaces("") & " " & CountSpaces(" "))
End Sub
End ModuleCountSpaces.Output
2 0 3
No base case: the stack overflows
Short code B4·7·21
import sys
def Countdown(N): # no base case
return Countdown(N - 1)
print("Limit:", sys.getrecursionlimit())
try:
Countdown(5)
except RecursionError as Error:
print("RecursionError:", Error)RecursionError, which a try can catch.Output
Limit: 1000 RecursionError: maximum recursion depth exceeded
public class Main {
static int Countdown(int N) { // no base case
return Countdown(N - 1);
}
public static void main(String[] args) {
try {
Countdown(5);
} catch (StackOverflowError Error) {
System.out.println(Error);
}
}
}StackOverflowError, which a catch can still catch.Output
java.lang.StackOverflowError
Module Program
Function Countdown(N As Integer) As Integer ' no base case
Return Countdown(N - 1)
End Function
Sub Main()
Console.WriteLine("Start")
Console.WriteLine(Countdown(5))
End Sub
End ModuleStack overflow. and names the repeated call, Countdown(Int32). A stack overflow cannot be caught in .NET, so Start is the only line the program prints.The cost of recursion
Short code B4·7·22
def SumTo(N):
if N == 0:
return 0
else:
return N + SumTo(N - 1)
def SumToLoop(N):
Total = 0
for Count in range(1, N + 1):
Total = Total + Count
return Total
for N in [100, 900, 5000]:
try:
print(N, SumTo(N))
except RecursionError:
print(N, "RecursionError")
print(5000, SumToLoop(5000))SumTo(5000) fails although it has a base case. The loop needs one frame however large N is.Output
100 5050 900 405450 5000 RecursionError 5000 12502500
public class Main {
static long SumTo(long N) {
if (N == 0) {
return 0;
} else {
return N + SumTo(N - 1);
}
}
static long SumToLoop(long N) {
long Total = 0;
for (long Count = 1; Count <= N; Count++) {
Total = Total + Count;
}
return Total;
}
public static void main(String[] args) {
System.out.println(5000 + " " + SumTo(5000));
try {
System.out.println(SumTo(1000000));
} catch (StackOverflowError Error) {
System.out.println(1000000 + " " + Error);
}
System.out.println(1000000 + " " + SumToLoop(1000000));
}
}long, because the total is too big for an int).Output
5000 12502500 1000000 java.lang.StackOverflowError 1000000 500000500000
Command words and evidence for recursion
Short code B4·7·23
Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.
Workbook 4: Recursion
Short code W4·7 · Practical Programming Task Book
The write-in workbook for this chapter has drills, exam-style practice, trace tables, fix-the-mistake and mark-it-yourself pages. Its full mark schemes and an interactive version arrive here with the chapter.
Starter files
Short code W4·7·K
Data files and skeleton code in Python, VB.NET, Java for this chapter's tasks arrive here with the chapter.


