Python Programming · High School (9–10) · 1 course, 17 worked problems, 26 practice questions
A recursive function is a function that calls itself. It solves a problem by solving a smaller copy of the same problem. Every recursive function needs a base case, which stops the calls, and a recursive case, which moves towards the base case. For example, the factorial of is times the factorial of , and the factorial of 0 is 1. Without a base case, Python stops with a RecursionError. Recursion suits problems with a nested shape, such as the Fibonacci numbers, the Tower of Hanoi and folders inside folders.
Choose an answer, then check it. Each one shows a full explanation.
The function mirror moves the last letter of a text to the front and the first letter to the back, and does the same to the letters between them by calling itself.
def mirror(s):
if len(s) <= 1:
return s
return s[-1] + mirror(s[1:-1]) + s[0]
print(mirror("stream"))
What does the program print?
A recursive function works on a shorter and shorter slice of a list. def walk(v): if len(v) == 1: return v return walk(v[1:]) + [v[0]] print(walk([1, 2, 3, 4])) What does the program print?
Three small functions are defined. Two of them call themselves, and one uses a loop.
def a(n):
if n == 0:
return 0
return n + a(n - 1)
def b(n):
total = 0
for k in range(n):
total += k
return total
def d(n):
if n <= 1:
return n
return n * d(n - 1)
Which of these expressions are True? Choose every correct option.
One or more options are correct. Tick all the correct ones: a wrong option costs marks, and a part-right answer earns part of the marks.
A recursive function calls itself twice for each number that is two or more, and adds one each time. def calls(n): if n < 2: return 1 return calls(n - 1) + calls(n - 2) + 1 print(calls(4)) What does the program print?
A function multiplies its argument by its own result for a number two smaller, and stops at one or less. def f(n): if n <= 1: return 1 return n * f(n - 2) print(f(5), f(6), f(1)) What is printed?
A function counts calls to itself, and its only way out is a test for exactly zero. def steps(n): if n == 0: return 0 return 1 + steps(n - 2) print(steps(5)) What is the result of running this program?
def m(n) returns n when n < 10, and otherwise m(n // 10). What is m(4729)?
def g(n): if n == 1, return 1; else return 2 * g(n - 1). What is g(5)?
A recursive function on a list returns 0 for []. For a longer list it returns 1 + itself on items[1:]. What does it work out?
def p(n): print(n), then p(n - 1) if n > 1. How many lines does p(5) show?
Each one has a hint, the key idea and a full worked solution.