MathubLearn / Practice / Excel
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

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

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.