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.
Chapters
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.
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([]))True
False
False- The two
ifblocks are the base cases: an empty list (no 0 can be in it) and a list whose first element is 0. - The
elseis the recursive step: check the rest of the list, excluding the first element.L[1:len(L)]is the same asL[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:
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]))check0([3, 0, 5])
check0([0, 5])
True
check0([1, 2])
check0([2])
check0([])
FalseEvery 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)
import sys
print(sys.getrecursionlimit())1000Python allows about 1000 nested calls. check0 makes one call per element, so a long list without a 0 runs out:
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))False
RecursionError: maximum recursion depth exceededA loop has no such limit, and Python's own in does the same job:
def check0_loop(L):
for x in L:
if x == 0:
return True
return False
print(check0_loop([1] * 1500), 0 in [1, 0])False TrueL[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
- Name the base cases first, then the recursive step.
- To trace, write one line per call with the list it receives.
- Forgetting the empty-list base case, which makes
L[0]fail. - Recursing on
Linstead ofL[1:]: the list never shrinks.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
What does the program print?
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]))Add 1 for every negative first element.
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]))3- -1, -5 and -9 are negative.
- Answer: 3
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
def g(L):
if len(L) == 0:
return []
return g(L[1:]) + [L[0]]
print(g([1, 2, 3]))[1, 2, 3][3, 2, 1][1]The first element is added after the rest.
def g(L):
if len(L) == 0:
return []
return g(L[1:]) + [L[0]]
print(g([1, 2, 3]))[3, 2, 1]g([1, 2, 3])=g([2, 3]) + [1]=[3, 2] + [1].- Answer: option 2.
Numerical Answer Type (NAT).
How many times is check0 called?
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)Stop at the first 0.
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)3- Calls on
[4, 8, 0, 2],[8, 0, 2],[0, 2]; the third finds 0. - Answer: 3
L[0] == 0: True
Else: check0(L[1:])
RecursionError beyond
0 in L
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
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))[2, 5, 6, 7, 19, 59]mini(L)finds the minimum with a plain loop (the variable inside is also calledmini; 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
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])take 2, sort the rest [9, 5]
take 5, sort the rest [9]
Sort([9]) -> [9]
returns [5, 9]
returns [2, 5, 9]2.3A side effect (extra)
L.remove(m) changes the list that was passed in. Look at L after the call:
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)[2, 5, 6, 7, 19, 59]
[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:
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)[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 / 2comparisons, like comparing every pair in CT Week 4. - There is one recursive call per element, so long lists hit the recursion limit:
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)))RecursionError: maximum recursion depth exceededFor real work, Python's built-in sorted() has neither problem.
2.5Exam tips and common mistakes
- Trace by writing the minimum and the remaining list at each level.
- Remember duplicates:
removetakes out only one copy.
- 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)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
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, 3, 4] [4, 1, 3][1, 3, 4] [1, 3, 4][1, 3, 4] [4][1, 3, 4] []remove changes data itself.
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, 3, 4] [4]- The result is sorted; data keeps only its largest item.
- Answer: option 3.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
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, 2, 3, 3][1, 2, 3][3, 3, 2, 1]remove takes out one copy at a time.
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, 2, 3, 3]- Both 3s survive, one per level.
- Answer: option 1.
m = mini(L)
[m] + Sort(rest)
Caller left with [59]
Pass L[:]
Depth n: RecursionError
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
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.
- Set two pointers,
lowandhigh, at the lowest and highest positions of the list. - Find the middle position
mid = (low + high) // 2and look atlist[mid]. - If
x == list[mid], it is found. Else comparexwith it. - If
x > list[mid], search the right side:low = mid + 1. - Else search the left side:
high = mid - 1. - Repeat steps 2 to 5 until low passes high.
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 - 1low 0 high 6 mid 3 L[mid] 6
low 0 high 2 mid 1 L[mid] 4
found at index 14 < 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:
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")7 items: 2 halvings
1000 items: 9 halvings
1000000 items: 19 halvingsA million sorted items need about 20 comparisons; checking them one by one could need a million.
3.4Exam tips and common mistakes
- Write low, high and mid as a table, one row per step.
- mid is a position; compare
list[mid], not mid.
- Using binary search on an unsorted list.
- Comparing x with the index instead of the value.
- Forgetting the
+ 1/- 1when moving low or high.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
L = [10, 20, 30, 40, 50, 60, 70, 80, 90]
low, high = 0, len(L) - 1
mid = (low + high) // 2
print(mid, L[mid])mid is (0 + 8) // 2.
L = [10, 20, 30, 40, 50, 60, 70, 80, 90]
low, high = 0, len(L) - 1
mid = (low + high) // 2
print(mid, L[mid])4 50- Position 4 holds 50.
- Answer: option 2.
mid = (low + high) // 2
Discard half
Not 9
1,000,000: about 20
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
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))True
Falsebeginandendstart 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.
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))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:
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))IndexError: list index out of rangeFor 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:
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])False
True4.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:
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))1 -1 -14.5Exam tips and common mistakes
- 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].
- Forgetting the check after the loop.
- Calling it on an empty list.
- Using it on unsorted data.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
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))The list is not sorted.
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))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.
Numerical Answer Type (NAT).
How many times does the loop body run before 11 is found?
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)Trace begin, end, mid.
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)2- Pass 1: mid 3 (value 7), 7 < 11 so begin = 4. Pass 2: mid 5 (value 11), found.
- Answer: 2
mid = (begin + end) // 2
Move begin or end
Then True or False
Unsorted: wrong answer
Binary Search: Recursive Method
Two base cases, one recursive call on a smaller range, and how it compares with the loop.
5.1The program
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))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
midexactly as the loop does, and call the function again on the smaller range. - The first call must cover the whole list:
begin = 0andend = len(L) - 1. The source does not show a call; the run above does.
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
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))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]
False16 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.
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_search | rbinary_search | |
|---|---|---|
| Repeats by | a while loop | calling itself |
| Range kept in | begin, end variables | begin, end parameters |
| Stops when | end - begin ≤ 1 | base cases: one or two items |
| Same | middle element, halving, final check | middle element, halving, final check |
| Empty list | IndexError | returns False |
5.4Exam tips and common mistakes
- Start the trace with begin = 0, end = len(L) - 1.
- Each call: base case? If not, narrow and recurse.
- Calling it with end = len(L) instead of len(L) - 1.
- Forgetting to return the recursive call's result.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
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))One value is in the list, one is not.
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))True False- 8 is found; 5 is not in the list.
- Answer: option 1.
end - begin == 1
Call itself
Far below the limit
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.
Write a recursive function checkVal(L, v) that returns True if v is anywhere in the list L, following the same pattern as check0.
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))True
FalseWrite a recursive function to sum all the elements of a list, without using the built-in sum().
def recSum(L):
if (len(L) == 0):
return 0
return L[0] + recSum(L[1:])
print(recSum([1, 2, 3, 4]))
print(recSum([]))10
0Base case: the empty list sums to 0.
Write a recursive function to find the maximum element of a list, similar in spirit to mini(L).
The source's solution:
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)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:
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)9
[4, 9, 2]Trace Sort([9, 2, 5]) step by step: write out each recursive call and what it returns.
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])take 2, sort the rest [9, 5]
take 5, sort the rest [9]
Sort([9]) -> [9]
returns [5, 9]
returns [2, 5, 9]Given [2, 4, 6, 8, 10, 12, 14] and x = 10, work out low, high and mid at each step until x is found.
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 - 1low 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
foundRun binary_search on [1, 3, 5, 7, 9] looking for 4, and explain at which point the function returns False.
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))FalseAfter 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.
Explain, in your own words, what changes between binary_search and rbinary_search, and what stays the same.
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.
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
| Concept | Key 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: precondition | The list must already be sorted. |
| Binary search: core idea | Compare the target with the middle element; discard the half it cannot be in. |
| Iterative method | A while loop with begin / end pointers that move inward. |
| Recursive method | Divide and conquer: each halving is a fresh recursive call. |
| Algorithm | Approach | Needs sorted input? | Work |
|---|---|---|---|
| Recursive selection sort | Find min, remove, recurse on the rest | No: it produces the sorted order | about n × n / 2 comparisons, depth n |
| Binary search (iterative) | While loop, shrink the range each pass | Yes | about log₂ n passes |
| Binary search (recursive) | A recursive call per halving | Yes | about log₂ n calls |
Patterns and how to use them
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.
- Base case: the empty list.
- Recursive step on
L[1:]. - Combine the first item with that answer.
def recSum(L):
if len(L) == 0:
return 0
return L[0] + recSum(L[1:])
print(recSum([5, 6, 7]))18result = Sort(L[:])Use whenA function changes its argument but you still need the original.
- Pass
L[:](a copy). - Use the returned list.
- The original is untouched.
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)[1, 2, 3] [3, 1, 2]while low <= high:
mid = (low + high) // 2
...Use whenSearching a sorted list quickly.
- Start with the whole list.
- Compare with
L[mid]; keep the half that can hold x. - Stop when found or when the range is empty.
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 - 1index 3def rb(L, k, b, e):
if b > e:
return False
m = (b + e) // 2
...Use whenThe same search, written as divide and conquer.
- Base case: an empty range.
- Compare with the middle.
- Recurse on the half that can hold k.
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))True False7.2Common errors to avoid
| Mistake | What Python says |
|---|---|
check0 on 1500 items | RecursionError: maximum recursion depth exceeded |
Sort on 1500 items | RecursionError: maximum recursion depth exceeded |
binary_search([], 3) | IndexError: list index out of range |
| Mistake | Correct idea |
|---|---|
| No base case, or one never reached | The input must shrink towards the base case on every call. |
Expecting Sort(L) to leave L alone | It removes items from L; pass L[:]. |
| Binary search on unsorted data | Sort first; otherwise the answer can be wrong. |
| "x (4) < mid (9)" in the source | The middle of [3, 4, 5, 6, 7, 8, 9] is 6. |
| Recursive call without the first range | Start 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)andSort(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
Recurse on L[1:]
Depth limit
Side effect on L
About n × n / 2
Middle element
About log2 n
recursive call
Same halving