Weeks
Intro to PythonWeek 8 · Recursive Programs and Binary Search
Week 8 Notes

Python,
Week 8

Recursive programs on lists, a recursive selection sort, and binary search in both its iterative and recursive forms, with every trace really run.

7 chapters16 worked examples~29 min read
RecursionSelection sortBinary searchIterativeDivide and conquer

Chapters

  1. 01Recursive Programs: Finding 0 in a ListPart 1
  2. 02Sorting RecursivelyPart 2
  3. 03Binary Search: the Idea and the WorkingParts 3-4
  4. 04Binary Search: Iterative MethodPart 5
  5. 05Binary Search: Recursive MethodPart 6
  6. 06Try It YourselfPractice zone
  7. 07Week 8 Summary SheetAll parts
01
Recursion

Recursive Programs: Finding 0 in a List

check0: two base cases and a recursive step on the rest of the list.

Detailed recursion notes (base case, how recursion works, advantages and disadvantages) are in Week 5. This week builds on them with worked recursive programs on lists.

1.1Finding 0 in a list

Program: find whether 0 is present in a list, using recursion.

Python
def check0(L):
    if (len(L) == 0):        # if the list is empty, return False
        return False
    if (L[0] == 0):          # if first element is zero, return True
        return True
    else:
        return check0(L[1:len(L)])
        # checks the rest of the list, excluding the first element

print(check0([3, 0, 5]))
print(check0([1, 2]))
print(check0([]))
Output
True
False
False
  • The two if blocks are the base cases: an empty list (no 0 can be in it) and a list whose first element is 0.
  • The else is the recursive step: check the rest of the list, excluding the first element. L[1:len(L)] is the same as L[1:].
  • Each call either resolves immediately or shrinks the problem by one element and calls itself again.

1.2Watching the calls

The same function with one extra line that prints each call, indented by depth:

Python
def check0(L, depth=0):
    print("  " * depth + "check0(" + str(L) + ")")
    if len(L) == 0:
        return False
    if L[0] == 0:
        return True
    return check0(L[1:], depth + 1)

print(check0([3, 0, 5]))
print(check0([1, 2]))
Output
check0([3, 0, 5])
  check0([0, 5])
True
check0([1, 2])
  check0([2])
    check0([])
False
calls go downanswers come back upcheck0([3, 0, 5])check0([0, 5])→ Truebase case: L[0] == 0check0([1, 2])check0([2])check0([])→ Falsebase case: empty list
Figure 1. Each call works on a shorter list until a base case answers; the answer is handed back up unchanged
Key idea

Every recursive function needs a base case that is certain to be reached. Here the list gets one shorter on each call, so it must eventually be empty.

1.3How deep can it go? (extra)

Python
import sys
print(sys.getrecursionlimit())
Output
1000

Python allows about 1000 nested calls. check0 makes one call per element, so a long list without a 0 runs out:

Python
def check0(L):
    if (len(L) == 0):        # if the list is empty, return False
        return False
    if (L[0] == 0):          # if first element is zero, return True
        return True
    else:
        return check0(L[1:len(L)])
        # checks the rest of the list, excluding the first element

print(check0([1] * 900))
print(check0([1] * 1500))
Error
False
RecursionError: maximum recursion depth exceeded

A loop has no such limit, and Python's own in does the same job:

Python
def check0_loop(L):
    for x in L:
        if x == 0:
            return True
    return False

print(check0_loop([1] * 1500), 0 in [1, 0])
Output
False True
Slicing costs too (extra). L[1:] copies the rest of the list on every call. That is fine for learning recursion; for large lists the loop is both safer and faster.

1.4Exam tips and common mistakes

Exam tips
  • Name the base cases first, then the recursive step.
  • To trace, write one line per call with the list it receives.
Common mistakes
  • Forgetting the empty-list base case, which makes L[0] fail.
  • Recursing on L instead of L[1:]: the list never shrinks.

Practice questions (graded-assignment style)

Q1Counting negatives

Numerical Answer Type (NAT).

What does the program print?

Python
def f(L):
    if len(L) == 0:
        return 0
    if L[0] < 0:
        return 1 + f(L[1:])
    return f(L[1:])

print(f([3, -1, 4, -5, -9]))
Solution
Idea

Add 1 for every negative first element.

Python
def f(L):
    if len(L) == 0:
        return 0
    if L[0] < 0:
        return 1 + f(L[1:])
    return f(L[1:])

print(f([3, -1, 4, -5, -9]))
Output
3
  • -1, -5 and -9 are negative.
  • Answer: 3
Q2Reversing

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
def g(L):
    if len(L) == 0:
        return []
    return g(L[1:]) + [L[0]]

print(g([1, 2, 3]))
1
[1, 2, 3]
2
[3, 2, 1]
3
[1]
4
An error
Solution
Idea

The first element is added after the rest.

Python
def g(L):
    if len(L) == 0:
        return []
    return g(L[1:]) + [L[0]]

print(g([1, 2, 3]))
Output
[3, 2, 1]
  • g([1, 2, 3]) = g([2, 3]) + [1] = [3, 2] + [1].
  • Answer: option 2.
Q3Number of calls

Numerical Answer Type (NAT).

How many times is check0 called?

Python
count = 0
def check0(L):
    global count
    count += 1
    if len(L) == 0:
        return False
    if L[0] == 0:
        return True
    return check0(L[1:])

check0([4, 8, 0, 2])
print(count)
Solution
Idea

Stop at the first 0.

Python
count = 0
def check0(L):
    global count
    count += 1
    if len(L) == 0:
        return False
    if L[0] == 0:
        return True
    return check0(L[1:])

check0([4, 8, 0, 2])
print(count)
Output
3
  • Calls on [4, 8, 0, 2], [8, 0, 2], [0, 2]; the third finds 0.
  • Answer: 3
Revision overview
check0Empty: False
L[0] == 0: True
Else: check0(L[1:])
Recursive programsPart 1
DepthLimit about 1000
RecursionError beyond
AlternativesA for loop
0 in L
Revision: a recursive search on a list
Next · RecursionSorting Recursively
02
Recursion

Sorting Recursively

Recursive selection sort: take the minimum, sort the rest, and watch the side effect.

A recursive version of selection sort: repeatedly find the minimum of what is left, remove it, and recursively sort the remainder.

2.1The program

Python
def mini(L):
    # finds the minimum element in the list
    mini = L[0]
    for x in L:
        if (x < mini):
            mini = x
    return mini

def Sort(L):
    # recursively sorts the list
    if (L == []) or (len(L) == 1):
        return L
    m = mini(L)
    # m now contains the minimum element in L
    L.remove(m)
    # we remove that element from L
    return [m] + Sort(L)
    # we recursively sort the smaller list

L = [5, 6, 59, 19, 2, 7]
print(Sort(L))
Output
[2, 5, 6, 7, 19, 59]
  • mini(L) finds the minimum with a plain loop (the variable inside is also called mini; that is allowed, but a different name would be clearer).
  • Base case: an empty list or a list with one item is already sorted.
  • Recursive step: pull out the smallest element and put it in front of the sorted rest: [m] + Sort(L).

2.2Tracing a small sort

Python
def Sort(L, depth=0):
    pad = "  " * depth
    if L == [] or len(L) == 1:
        print(pad + "Sort(" + str(L) + ") -> " + str(L))
        return L
    m = min(L)
    L.remove(m)
    print(pad + "take " + str(m) + ", sort the rest " + str(L))
    result = [m] + Sort(L, depth + 1)
    print(pad + "returns " + str(result))
    return result

Sort([9, 2, 5])
Output
take 2, sort the rest [9, 5]
  take 5, sort the rest [9]
    Sort([9]) -> [9]
  returns [5, 9]
returns [2, 5, 9]
take the minimum → sort the rest[925]m = 2[95]m = 5[9]join on the way back[9][59][259]
Figure 2. Take the minimum on the way down, join the results on the way back

2.3A side effect (extra)

L.remove(m) changes the list that was passed in. Look at L after the call:

Python
def mini(L):
    # finds the minimum element in the list
    mini = L[0]
    for x in L:
        if (x < mini):
            mini = x
    return mini

def Sort(L):
    # recursively sorts the list
    if (L == []) or (len(L) == 1):
        return L
    m = mini(L)
    # m now contains the minimum element in L
    L.remove(m)
    # we remove that element from L
    return [m] + Sort(L)
    # we recursively sort the smaller list

L = [5, 6, 59, 19, 2, 7]
print(Sort(L))
print(L)
Output
[2, 5, 6, 7, 19, 59]
[59]
L before[56591927]Sort(L) returns[25671959]L afterwards[59]L.remove(m) changed the caller's list
Figure 3. Sort returns the sorted list, but the caller's L is left as [59]

Each level removes one element from the same list object, so only the last item survives. This is the side effect of Computational Thinking Week 8 and the parameter passing of Week 6. Passing a copy keeps the original:

Python
def mini(L):
    # finds the minimum element in the list
    mini = L[0]
    for x in L:
        if (x < mini):
            mini = x
    return mini

def Sort(L):
    # recursively sorts the list
    if (L == []) or (len(L) == 1):
        return L
    m = mini(L)
    # m now contains the minimum element in L
    L.remove(m)
    # we remove that element from L
    return [m] + Sort(L)
    # we recursively sort the smaller list

L = [5, 6, 59, 19, 2, 7]
print(Sort(L[:]))
print(L)
Output
[2, 5, 6, 7, 19, 59]
[5, 6, 59, 19, 2, 7]

2.4Cost and depth (extra)

  • Each level scans the remaining list to find the minimum: n + (n − 1) + ... about n × n / 2 comparisons, like comparing every pair in CT Week 4.
  • There is one recursive call per element, so long lists hit the recursion limit:
Python
def mini(L):
    # finds the minimum element in the list
    mini = L[0]
    for x in L:
        if (x < mini):
            mini = x
    return mini

def Sort(L):
    # recursively sorts the list
    if (L == []) or (len(L) == 1):
        return L
    m = mini(L)
    # m now contains the minimum element in L
    L.remove(m)
    # we remove that element from L
    return [m] + Sort(L)
    # we recursively sort the smaller list

big = list(range(1500, 0, -1))
print(len(Sort(big)))
Error
RecursionError: maximum recursion depth exceeded

For real work, Python's built-in sorted() has neither problem.

2.5Exam tips and common mistakes

Exam tips
  • Trace by writing the minimum and the remaining list at each level.
  • Remember duplicates: remove takes out only one copy.
Common mistakes
  • Expecting the original list to be unchanged.
  • Forgetting the one-item base case.
  • Writing Sort(L) + [m], which puts the minimum last.

Practice questions (graded-assignment style)

Q1After the sort

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
def Sort(L):
    if L == [] or len(L) == 1:
        return L
    m = min(L)
    L.remove(m)
    return [m] + Sort(L)

data = [4, 1, 3]
s = Sort(data)
print(s, data)
1
[1, 3, 4] [4, 1, 3]
2
[1, 3, 4] [1, 3, 4]
3
[1, 3, 4] [4]
4
[1, 3, 4] []
Solution
Idea

remove changes data itself.

Python
def Sort(L):
    if L == [] or len(L) == 1:
        return L
    m = min(L)
    L.remove(m)
    return [m] + Sort(L)

data = [4, 1, 3]
s = Sort(data)
print(s, data)
Output
[1, 3, 4] [4]
  • The result is sorted; data keeps only its largest item.
  • Answer: option 3.
Q2Duplicates

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
def Sort(L):
    if L == [] or len(L) == 1:
        return L
    m = min(L)
    L.remove(m)
    return [m] + Sort(L)

print(Sort([3, 1, 3, 2]))
1
[1, 2, 3, 3]
2
[1, 2, 3]
3
[3, 3, 2, 1]
4
An error
Solution
Idea

remove takes out one copy at a time.

Python
def Sort(L):
    if L == [] or len(L) == 1:
        return L
    m = min(L)
    L.remove(m)
    return [m] + Sort(L)

print(Sort([3, 1, 3, 2]))
Output
[1, 2, 3, 3]
  • Both 3s survive, one per level.
  • Answer: option 1.
Revision overview
Sort(L)Base: 0 or 1 items
m = mini(L)
[m] + Sort(rest)
Recursive sortPart 2
Side effectL.remove(m)
Caller left with [59]
Pass L[:]
CostAbout n × n / 2
Depth n: RecursionError
Revision: recursive selection sort and its side effect
Next · Binary searchBinary Search: the Idea and the Working
03
Binary search

Binary Search: the Idea and the Working

A sorted list, a middle element, and half the list discarded at every step.

3.1What binary search is

Binary search

A searching algorithm for finding an element in a sorted list. The element is always searched for in the middle of a portion of the list, and the half it cannot be in is discarded.

  • Binary search can be implemented only on a sorted list of items.
  • If the elements are not sorted already, we need to sort them first.
  • It can be implemented in two ways: the iterative method and the recursive method.
  • The recursive method follows the divide and conquer approach.

3.2Step-by-step working

List to search: [3, 4, 5, 6, 7, 8, 9], element x = 4.

  1. Set two pointers, low and high, at the lowest and highest positions of the list.
  2. Find the middle position mid = (low + high) // 2 and look at list[mid].
  3. If x == list[mid], it is found. Else compare x with it.
  4. If x > list[mid], search the right side: low = mid + 1.
  5. Else search the left side: high = mid - 1.
  6. Repeat steps 2 to 5 until low passes high.
Python
L = [3, 4, 5, 6, 7, 8, 9]
x = 4
low, high = 0, len(L) - 1
while low <= high:
    mid = (low + high) // 2
    print("low", low, "high", high, "mid", mid, "L[mid]", L[mid])
    if L[mid] == x:
        print("found at index", mid)
        break
    elif x > L[mid]:
        low = mid + 1
    else:
        high = mid - 1
Output
low 0 high 6 mid 3 L[mid] 6
low 0 high 2 mid 1 L[mid] 4
found at index 1
x = 430415263748596lowhigh30415263748596lowhighstep 1:mid = index 3 (value 6): 4 < 6, keep the leftstep 2:mid = index 1 (value 4): found
Figure 4. Searching for 4: the middle element is 6, so only the left part [3, 4, 5] is kept
Correction. The source's worked diagram says "x (4) < mid (9)". The middle element is 6 (index 3), not 9; it is 4 < 6 that sends the search to the left half [3, 4, 5], as the run shows.

3.3How many steps? (extra)

Each step throws away about half of what is left, so the number of steps grows with log₂ n, not with n:

Python
def steps_needed(n, k):
    L = list(range(n))
    begin, end, steps = 0, n - 1, 0
    while end - begin > 1:
        steps += 1
        mid = (begin + end) // 2
        if L[mid] == k:
            return steps
        if L[mid] > k:
            end = mid - 1
        if L[mid] < k:
            begin = mid + 1
    return steps

for n in [7, 1000, 1000000]:
    print(n, "items:", steps_needed(n, n - 1), "halvings")
Output
7 items: 2 halvings
1000 items: 9 halvings
1000000 items: 19 halvings
each step halves the range1684211,000,000 items: about 20 halvings
Figure 5. Halving: 16, 8, 4, 2, 1

A million sorted items need about 20 comparisons; checking them one by one could need a million.

3.4Exam tips and common mistakes

Exam tips
  • Write low, high and mid as a table, one row per step.
  • mid is a position; compare list[mid], not mid.
Common mistakes
  • Using binary search on an unsorted list.
  • Comparing x with the index instead of the value.
  • Forgetting the + 1 / - 1 when moving low or high.

Practice questions (graded-assignment style)

Q1The first middle

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
L = [10, 20, 30, 40, 50, 60, 70, 80, 90]
low, high = 0, len(L) - 1
mid = (low + high) // 2
print(mid, L[mid])
1
4 40
2
4 50
3
5 50
4
5 60
Solution
Idea

mid is (0 + 8) // 2.

Python
L = [10, 20, 30, 40, 50, 60, 70, 80, 90]
low, high = 0, len(L) - 1
mid = (low + high) // 2
print(mid, L[mid])
Output
4 50
  • Position 4 holds 50.
  • Answer: option 2.
Revision overview
PreconditionSorted list only
Stepslow, high
mid = (low + high) // 2
Discard half
Binary searchParts 3-4
CorrectionMiddle of [3..9] is 6
Not 9
SpeedAbout log2 n steps
1,000,000: about 20
Revision: the idea of binary search
Next · Binary searchBinary Search: Iterative Method
04
Binary search

Binary Search: Iterative Method

A while loop with begin and end moving inward, then a direct check of the last one or two items.

4.1The program

Python
def binary_search(L, k):
    begin = 0              # first element in L, L[0]
    end = len(L) - 1       # last element in L, L[len(L)-1]
    while (end - begin > 1):
        # 0, 1 or 2 elements left are handled after the loop
        mid = (begin + end) // 2
        if (L[mid] == k):          # if mid is indeed k,
            return True            # return True and stop
        if (L[mid] > k):           # mid element greater than k:
            end = mid - 1          # check on the left side
        if (L[mid] < k):           # mid element less than k:
            begin = mid + 1        # check on the right side
    # here end - begin is 1 or less: check what is left
    if (L[begin] == k) or (L[end] == k):
        return True
    else:
        return False

L = [3, 4, 5, 6, 7, 8, 9]
print(binary_search(L, 4))
print(binary_search(L, 10))
Output
True
False
  • begin and end start at the two ends and move inward.
  • The loop runs while there are more than two elements in the range (end - begin > 1).
  • When the loop stops, at most two elements are left, and both are checked directly.

4.2Two traces

The same function with a print in the loop: first a search that succeeds, then one for a missing value.

Python
def binary_search(L, k):
    begin = 0
    end = len(L) - 1
    while end - begin > 1:
        mid = (begin + end) // 2
        print("begin", begin, "end", end, "mid", mid, "L[mid]", L[mid])
        if L[mid] == k:
            return True
        if L[mid] > k:
            end = mid - 1
        if L[mid] < k:
            begin = mid + 1
    print("left over: L[" + str(begin) + "] =", L[begin], " L[" + str(end) + "] =", L[end])
    return L[begin] == k or L[end] == k

print(binary_search([2, 4, 6, 8, 10, 12, 14], 10))
print(binary_search([1, 3, 5, 7, 9], 4))
Output
begin 0 end 6 mid 3 L[mid] 8
begin 4 end 6 mid 5 L[mid] 12
left over: L[4] = 10  L[4] = 10
True
begin 0 end 4 mid 2 L[mid] 5
left over: L[0] = 1  L[1] = 3
False
  • Searching 10 in [2, 4, 6, 8, 10, 12, 14]: two halvings leave only index 4, which holds 10.
  • Searching 4 in [1, 3, 5, 7, 9]: one halving leaves indices 0 and 1 (values 1 and 3), which straddle 4 without matching it, so the function returns False.

4.3Edge cases (extra)

The function was checked against Python's in on every sorted list of 1 to 39 items, and on thousands of sorted lists with repeated values: it always agreed. Two cases still need care:

Python
def binary_search(L, k):
    begin = 0              # first element in L, L[0]
    end = len(L) - 1       # last element in L, L[len(L)-1]
    while (end - begin > 1):
        # 0, 1 or 2 elements left are handled after the loop
        mid = (begin + end) // 2
        if (L[mid] == k):          # if mid is indeed k,
            return True            # return True and stop
        if (L[mid] > k):           # mid element greater than k:
            end = mid - 1          # check on the left side
        if (L[mid] < k):           # mid element less than k:
            begin = mid + 1        # check on the right side
    # here end - begin is 1 or less: check what is left
    if (L[begin] == k) or (L[end] == k):
        return True
    else:
        return False

print(binary_search([], 3))
Error
IndexError: list index out of range

For an empty list the loop is skipped and L[0] does not exist. A first line if len(L) == 0: return False fixes it. And on an unsorted list the answer can simply be wrong:

Python
def binary_search(L, k):
    begin = 0              # first element in L, L[0]
    end = len(L) - 1       # last element in L, L[len(L)-1]
    while (end - begin > 1):
        # 0, 1 or 2 elements left are handled after the loop
        mid = (begin + end) // 2
        if (L[mid] == k):          # if mid is indeed k,
            return True            # return True and stop
        if (L[mid] > k):           # mid element greater than k:
            end = mid - 1          # check on the left side
        if (L[mid] < k):           # mid element less than k:
            begin = mid + 1        # check on the right side
    # here end - begin is 1 or less: check what is left
    if (L[begin] == k) or (L[end] == k):
        return True
    else:
        return False

print(binary_search([9, 1, 7, 3, 5], 9))
print(9 in [9, 1, 7, 3, 5])
Output
False
True

4.4Returning the position (extra)

The lecture's version returns True or False. The textbook form, closer to the step-by-step working of Chapter 3, returns the index (or -1), and handles the empty list:

Python
def search_index(L, x):
    low, high = 0, len(L) - 1
    while low <= high:
        mid = (low + high) // 2
        if L[mid] == x:
            return mid
        elif L[mid] < x:
            low = mid + 1
        else:
            high = mid - 1
    return -1

L = [3, 4, 5, 6, 7, 8, 9]
print(search_index(L, 4), search_index(L, 10), search_index([], 1))
Output
1 -1 -1

4.5Exam tips and common mistakes

Exam tips
  • Trace begin, end and mid each pass; stop when end - begin is 1 or less.
  • After the loop, check both L[begin] and L[end].
Common mistakes
  • Forgetting the check after the loop.
  • Calling it on an empty list.
  • Using it on unsorted data.

Practice questions (graded-assignment style)

Q1Unsorted input

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
def binary_search(L, k):
    begin = 0
    end = len(L) - 1
    while (end - begin > 1):
        mid = (begin + end) // 2
        if (L[mid] == k):
            return True
        if (L[mid] > k):
            end = mid - 1
        if (L[mid] < k):
            begin = mid + 1
    if (L[begin] == k) or (L[end] == k):
        return True
    else:
        return False

print(binary_search([5, 1, 4, 2, 3], 2))
1
True
2
False
3
An error
4
3
Solution
Idea

The list is not sorted.

Python
def binary_search(L, k):
    begin = 0
    end = len(L) - 1
    while (end - begin > 1):
        mid = (begin + end) // 2
        if (L[mid] == k):
            return True
        if (L[mid] > k):
            end = mid - 1
        if (L[mid] < k):
            begin = mid + 1
    if (L[begin] == k) or (L[end] == k):
        return True
    else:
        return False

print(binary_search([5, 1, 4, 2, 3], 2))
Output
False
  • mid 2 holds 4 > 2, so only indices 0 and 1 (5 and 1) are checked. 2 is in the list but never looked at.
  • Answer: option 2.
Q2Loop passes

Numerical Answer Type (NAT).

How many times does the loop body run before 11 is found?

Python
L = [1, 3, 5, 7, 9, 11, 13, 15]
begin, end, loops = 0, len(L) - 1, 0
while end - begin > 1:
    loops += 1
    mid = (begin + end) // 2
    if L[mid] == 11:
        break
    if L[mid] > 11:
        end = mid - 1
    if L[mid] < 11:
        begin = mid + 1
print(loops)
Solution
Idea

Trace begin, end, mid.

Python
L = [1, 3, 5, 7, 9, 11, 13, 15]
begin, end, loops = 0, len(L) - 1, 0
while end - begin > 1:
    loops += 1
    mid = (begin + end) // 2
    if L[mid] == 11:
        break
    if L[mid] > 11:
        end = mid - 1
    if L[mid] < 11:
        begin = mid + 1
print(loops)
Output
2
  • Pass 1: mid 3 (value 7), 7 < 11 so begin = 4. Pass 2: mid 5 (value 11), found.
  • Answer: 2
Revision overview
Loopwhile end - begin > 1
mid = (begin + end) // 2
Move begin or end
IterativePart 5
After the loopCheck L[begin], L[end]
Then True or False
CareEmpty list: IndexError
Unsorted: wrong answer
Revision: binary search with a while loop
Next · Binary searchBinary Search: Recursive Method
05
Binary search

Binary Search: Recursive Method

Two base cases, one recursive call on a smaller range, and how it compares with the loop.

5.1The program

Python
def rbinary_search(L, k, begin, end):
    """This will recursively compute binary search"""
    # one element left: just check L[begin]
    if (begin == end):
        if (L[begin] == k):
            return True
        else:
            return False
    # two elements left: check them individually
    if (end - begin == 1):
        if (L[begin] == k) or (L[end] == k):
            return True
        else:
            return False
    if (end - begin > 1):
        mid = (begin + end) // 2
        if (L[mid] > k):
            end = mid - 1          # discard the right, keep the left
        if (L[mid] < k):
            begin = mid + 1        # discard the left, keep the right
        if (L[mid] == k):
            return True
    if (end - begin < 0):
        return False
    # recursive step: search the narrowed-down range
    return rbinary_search(L, k, begin, end)

L = [3, 4, 5, 6, 7, 8, 9]
print(rbinary_search(L, 4, 0, len(L) - 1))
print(rbinary_search(L, 10, 0, len(L) - 1))
print(rbinary_search([], 3, 0, -1))
Output
True
False
False
  • Base case 1: begin == end, one element left: check it.
  • Base case 2: end - begin == 1, two elements left: check both.
  • Otherwise narrow the range around mid exactly as the loop does, and call the function again on the smaller range.
  • The first call must cover the whole list: begin = 0 and end = len(L) - 1. The source does not show a call; the run above does.
Divide and conquer

Each call solves the problem by solving a smaller copy of the same problem, half the size. Watch the base cases closely: one item and two items left are both checked directly; the recursive call happens only while the range has more than two items.

5.2Watching the calls

Python
def rbinary_search(L, k, begin, end, depth=0):
    print("  " * depth + "search L[" + str(begin) + ".." + str(end) + "]")
    if begin == end:
        return L[begin] == k
    if end - begin == 1:
        return L[begin] == k or L[end] == k
    mid = (begin + end) // 2
    if L[mid] == k:
        return True
    if L[mid] > k:
        end = mid - 1
    else:
        begin = mid + 1
    return rbinary_search(L, k, begin, end, depth + 1)

L = list(range(0, 32, 2))
print(rbinary_search(L, 26, 0, len(L) - 1))
print(rbinary_search(L, 27, 0, len(L) - 1))
Output
search L[0..15]
  search L[8..15]
    search L[12..15]
True
search L[0..15]
  search L[8..15]
    search L[12..15]
      search L[14..15]
False
rbinary_search(L, 26, ...) on L = [0, 2, ..., 30]L[0..15]L[7] = 14 < 26: keep the rightL[8..15]L[11] = 22 < 26: keep the rightL[12..15]L[13] = 26: found
Figure 6. Searching 26 in [0, 2, ..., 30]: three calls, each on a smaller range

16 items need at most 4 calls. The recursion depth is about log₂ n, so unlike check0 and Sort, binary search never comes near the recursion limit.

Two checks that never fire (extra). With a non-empty list, end - begin < 0 is never true after narrowing (checked on every list up to 59 items); it only catches an empty list, rbinary_search([], k, 0, -1), which returns False. Also, when L[mid] == k the range is not narrowed, so the order of the three ifs does not matter.

5.3Iterative and recursive side by side

binary_searchrbinary_search
Repeats bya while loopcalling itself
Range kept inbegin, end variablesbegin, end parameters
Stops whenend - begin ≤ 1base cases: one or two items
Samemiddle element, halving, final checkmiddle element, halving, final check
Empty listIndexErrorreturns False

5.4Exam tips and common mistakes

Exam tips
  • Start the trace with begin = 0, end = len(L) - 1.
  • Each call: base case? If not, narrow and recurse.
Common mistakes
  • Calling it with end = len(L) instead of len(L) - 1.
  • Forgetting to return the recursive call's result.

Practice questions (graded-assignment style)

Q1Two searches

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
def rbinary_search(L, k, begin, end):
    if begin == end:
        return L[begin] == k
    if end - begin == 1:
        return L[begin] == k or L[end] == k
    mid = (begin + end) // 2
    if L[mid] == k:
        return True
    if L[mid] > k:
        return rbinary_search(L, k, begin, mid - 1)
    return rbinary_search(L, k, mid + 1, end)

L = [2, 4, 6, 8, 10]
print(rbinary_search(L, 8, 0, 4), rbinary_search(L, 5, 0, 4))
1
True False
2
True True
3
False False
4
An error
Solution
Idea

One value is in the list, one is not.

Python
def rbinary_search(L, k, begin, end):
    if begin == end:
        return L[begin] == k
    if end - begin == 1:
        return L[begin] == k or L[end] == k
    mid = (begin + end) // 2
    if L[mid] == k:
        return True
    if L[mid] > k:
        return rbinary_search(L, k, begin, mid - 1)
    return rbinary_search(L, k, mid + 1, end)

L = [2, 4, 6, 8, 10]
print(rbinary_search(L, 8, 0, 4), rbinary_search(L, 5, 0, 4))
Output
True False
  • 8 is found; 5 is not in the list.
  • Answer: option 1.
Revision overview
Base casesbegin == end
end - begin == 1
Recursive stepNarrow around mid
Call itself
RecursivePart 6
Callrbinary_search(L, k, 0, len(L) - 1)
DepthAbout log2 n
Far below the limit
Revision: binary search by divide and conquer
Next · PracticeTry It Yourself
06
Practice

Try It Yourself

The seven tasks of the source, each with an executed solution.

Seven tasks from the source, to be done without looking back at the examples. Each has a really executed solution.

Task 1Recursive membership

Write a recursive function checkVal(L, v) that returns True if v is anywhere in the list L, following the same pattern as check0.

Solution
Python
def checkVal(L, v):
    if (len(L) == 0):
        return False
    if (L[0] == v):
        return True
    else:
        return checkVal(L[1:], v)

print(checkVal([3, 7, 9], 7))
print(checkVal([3, 7, 9], 4))
Output
True
False
Task 2Recursive sum

Write a recursive function to sum all the elements of a list, without using the built-in sum().

Solution
Python
def recSum(L):
    if (len(L) == 0):
        return 0
    return L[0] + recSum(L[1:])

print(recSum([1, 2, 3, 4]))
print(recSum([]))
Output
10
0

Base case: the empty list sums to 0.

Task 3Recursive max

Write a recursive function to find the maximum element of a list, similar in spirit to mini(L).

Solution

The source's solution:

Python
def maxi(L):
    m = L[0]
    for x in L:
        if (x > m):
            m = x
    return m

def recMax(L):
    if (len(L) == 1):
        return L[0]
    m = maxi(L)
    L.remove(m)
    return max(m, recMax(L)) if L else m

data = [4, 9, 2]
print(recMax(data))
print(data)
Output
9
[2]

It returns the right answer, but maxi(L) already finds the maximum with a loop, so the recursion adds nothing, and L.remove empties the caller's list. A recursive version that does the work through recursion and leaves the list alone:

Python
def recMax(L):
    if len(L) == 1:
        return L[0]
    rest = recMax(L[1:])        # maximum of everything after L[0]
    if L[0] > rest:
        return L[0]
    return rest

data = [4, 9, 2]
print(recMax(data))
print(data)
Output
9
[4, 9, 2]
Task 4Trace the recursive sort

Trace Sort([9, 2, 5]) step by step: write out each recursive call and what it returns.

Solution
Python
def Sort(L, depth=0):
    pad = "  " * depth
    if L == [] or len(L) == 1:
        print(pad + "Sort(" + str(L) + ") -> " + str(L))
        return L
    m = min(L)
    L.remove(m)
    print(pad + "take " + str(m) + ", sort the rest " + str(L))
    result = [m] + Sort(L, depth + 1)
    print(pad + "returns " + str(result))
    return result

Sort([9, 2, 5])
Output
take 2, sort the rest [9, 5]
  take 5, sort the rest [9]
    Sort([9]) -> [9]
  returns [5, 9]
returns [2, 5, 9]
Task 5Binary search by hand

Given [2, 4, 6, 8, 10, 12, 14] and x = 10, work out low, high and mid at each step until x is found.

Solution
Python
L = [2, 4, 6, 8, 10, 12, 14]
x = 10
low, high = 0, len(L) - 1
while low <= high:
    mid = (low + high) // 2
    print("low", low, "high", high, "mid", mid, "L[mid]", L[mid])
    if L[mid] == x:
        print("found")
        break
    elif x > L[mid]:
        low = mid + 1
    else:
        high = mid - 1
Output
low 0 high 6 mid 3 L[mid] 8
low 4 high 6 mid 5 L[mid] 12
low 4 high 4 mid 4 L[mid] 10
found
Task 6Searching for a missing value

Run binary_search on [1, 3, 5, 7, 9] looking for 4, and explain at which point the function returns False.

Solution
Python
def binary_search(L, k):
    begin = 0              # first element in L, L[0]
    end = len(L) - 1       # last element in L, L[len(L)-1]
    while (end - begin > 1):
        # 0, 1 or 2 elements left are handled after the loop
        mid = (begin + end) // 2
        if (L[mid] == k):          # if mid is indeed k,
            return True            # return True and stop
        if (L[mid] > k):           # mid element greater than k:
            end = mid - 1          # check on the left side
        if (L[mid] < k):           # mid element less than k:
            begin = mid + 1        # check on the right side
    # here end - begin is 1 or less: check what is left
    if (L[begin] == k) or (L[end] == k):
        return True
    else:
        return False

print(binary_search([1, 3, 5, 7, 9], 4))
Output
False

After one halving (mid 2 holds 5, so end = 1) only indices 0 and 1 are left; they hold 1 and 3, neither is 4, so the check after the loop returns False.

Task 7Iterative vs recursive

Explain, in your own words, what changes between binary_search and rbinary_search, and what stays the same.

Solution

Changes: the loop becomes a recursive call; begin and end become parameters; the stopping test becomes the two base cases. Stays the same: the sorted list, the middle element, discarding half the range, and the direct check of the last one or two items.

Next · All partsWeek 8 Summary Sheet
07
All parts

Week 8 Summary Sheet

One page to revise all of Week 8: recursion on lists, recursive sort and binary search.

7.1Recursion and binary search

ConceptKey idea
check0(L)Base cases: empty list → False, L[0] == 0 → True. Else recurse on L[1:].
Sort(L)Base case: L == [] or len(L) == 1. Else pull out the minimum, recurse on the rest.
Binary search: preconditionThe list must already be sorted.
Binary search: core ideaCompare the target with the middle element; discard the half it cannot be in.
Iterative methodA while loop with begin / end pointers that move inward.
Recursive methodDivide and conquer: each halving is a fresh recursive call.
AlgorithmApproachNeeds sorted input?Work
Recursive selection sortFind min, remove, recurse on the restNo: it produces the sorted orderabout n × n / 2 comparisons, depth n
Binary search (iterative)While loop, shrink the range each passYesabout log₂ n passes
Binary search (recursive)A recursive call per halvingYesabout log₂ n calls

Patterns and how to use them

Recursion on a list
Head and rest
main.py
def f(L):
    if len(L) == 0:
        return base_value
    return combine(L[0], f(L[1:]))

Use whenA list problem can be solved from its first item and the answer for the rest.

  1. Base case: the empty list.
  2. Recursive step on L[1:].
  3. Combine the first item with that answer.
ExampleSum of a list.
main.py
def recSum(L):
    if len(L) == 0:
        return 0
    return L[0] + recSum(L[1:])

print(recSum([5, 6, 7]))
Output
18
Sort without a side effect
Copy first
main.py
result = Sort(L[:])

Use whenA function changes its argument but you still need the original.

  1. Pass L[:] (a copy).
  2. Use the returned list.
  3. The original is untouched.
ExampleOriginal kept.
main.py
def Sort(L):
    if len(L) <= 1:
        return L
    m = min(L)
    L.remove(m)
    return [m] + Sort(L)

L = [3, 1, 2]
print(Sort(L[:]), L)
Output
[1, 2, 3] [3, 1, 2]
Binary search with a loop
Halve the range
main.py
while low <= high:
    mid = (low + high) // 2
    ...

Use whenSearching a sorted list quickly.

  1. Start with the whole list.
  2. Compare with L[mid]; keep the half that can hold x.
  3. Stop when found or when the range is empty.
ExampleIndex of 8.
main.py
L = [2, 4, 6, 8, 10]
low, high = 0, len(L) - 1
while low <= high:
    mid = (low + high) // 2
    if L[mid] == 8:
        print("index", mid)
        break
    elif L[mid] < 8:
        low = mid + 1
    else:
        high = mid - 1
Output
index 3
Binary search by recursion
Smaller range each call
main.py
def rb(L, k, b, e):
    if b > e:
        return False
    m = (b + e) // 2
    ...

Use whenThe same search, written as divide and conquer.

  1. Base case: an empty range.
  2. Compare with the middle.
  3. Recurse on the half that can hold k.
ExampleA compact version.
main.py
def rb(L, k, b, e):
    if b > e:
        return False
    m = (b + e) // 2
    if L[m] == k:
        return True
    if L[m] < k:
        return rb(L, k, m + 1, e)
    return rb(L, k, b, m - 1)

L = [1, 3, 5, 7]
print(rb(L, 7, 0, 3), rb(L, 4, 0, 3))
Output
True False

7.2Common errors to avoid

MistakeWhat Python says
check0 on 1500 itemsRecursionError: maximum recursion depth exceeded
Sort on 1500 itemsRecursionError: maximum recursion depth exceeded
binary_search([], 3)IndexError: list index out of range
MistakeCorrect idea
No base case, or one never reachedThe input must shrink towards the base case on every call.
Expecting Sort(L) to leave L aloneIt removes items from L; pass L[:].
Binary search on unsorted dataSort first; otherwise the answer can be wrong.
"x (4) < mid (9)" in the sourceThe middle of [3, 4, 5, 6, 7, 8, 9] is 6.
Recursive call without the first rangeStart with 0, len(L) - 1.

7.3Last-minute checklist

  • Writing check0(L): its two base cases and its recursive step
  • Recursive selection sort: how mini(L) and Sort(L) work together
  • Why binary search needs a sorted list
  • The step-by-step working: low, high, mid and how the range narrows
  • The iterative method: the while loop and its begin / end pointers
  • The recursive method: its base cases (begin == end, end - begin == 1)
  • Divide and conquer as the idea of recursive binary search
  • Tracing a binary search by hand on a small sorted list
Revision overview
check0Two base cases
Recurse on L[1:]
Depth limit
SortMin, remove, recurse
Side effect on L
About n × n / 2
Week 8Recursion and search
Binary searchSorted list
Middle element
About log2 n
Two formswhile loop
recursive call
Same halving
Revision: all of Week 8 on one page
Back to top