CSCI 127 Joy and Beauty of Data · Unit 1: Data types · on Exam 1
1.7 Recursion
Study notes for Recursion in CSCI 127 Joy and Beauty of Data at Montana State University: the big ideas, code you should know, a worked example, common mistakes and an exam tip. The same topic has endless practice questions and flashcards in Mathub.
Big ideas
- A recursive function calls itself on a smaller version of the problem. It needs a base case that answers directly and a recursive case that shrinks the input toward the base case.
- Classic shapes:
factorial(n) = n * factorial(n - 1)withfactorial(0) = 1; sum of a list = first item + sum of the rest; countdown; digit sum; powers. - Each call gets its own local variables and waits on the call stack until the deeper call returns. Too deep (no base case) gives
RecursionError. - Turtle recursion draws trees, spirals and snowflakes: draw one piece, then call yourself with a shorter length until it is too small.
- Anything recursive can be written with a loop; recursion is chosen when the problem is naturally self-similar.
Code you should know
Factorial and digit sum
def factorial(n):
if n == 0: # base case
return 1
return n * factorial(n - 1)
def digit_sum(n):
if n < 10:
return n
return n % 10 + digit_sum(n // 10)
print(factorial(5), digit_sum(4913))Output
120 17
Countdown shows the call order
def countdown(n):
if n == 0:
print("Liftoff!")
return
print(n)
countdown(n - 1)
print("back from", n)
countdown(3)Output
3 2 1 Liftoff! back from 1 back from 2 back from 3
A recursive turtle tree
import turtle
def branch(t, length):
if length < 10:
return
t.forward(length)
t.left(30)
branch(t, length * 0.7)
t.right(60)
branch(t, length * 0.7)
t.left(30)
t.backward(length)
t = turtle.Turtle()
t.left(90)
t.penup(); t.goto(0, -120); t.pendown()
t.color("darkgreen")
branch(t, 90)
t.hideturtle()Output
A branching tree.
Worked example
What does
mystery(4) return?def mystery(n):
if n <= 1:
return 1
return mystery(n - 1) + mystery(n - 2)Show the solution
5. mystery(2) = 1 + 1 = 2, mystery(3) = 2 + 1 = 3, mystery(4) = 3 + 2 = 5. It is the Fibonacci sequence.Common mistakes
- A base case that is never reached (for example shrinking by 2 from an odd number down past 0).
- Forgetting to
returnthe recursive call, so the answer is lost and the function returns None. - Not undoing turtle moves after a recursive branch, so the next branch starts in the wrong place.
Exam tipFor exam tracing, write the calls as a tree or a stack and resolve the deepest one first. Check the base case value before anything else.
Keep going in Mathub
Mathub is free for Montana State students: an endless quizzer with worked explanations, one-question lessons, flashcards, exam prep checklists, the class calendar with every deadline, a grade calculator and a study board for CSCI 127.