Challenge 5
- Algorithms course
- Expert
- Lesson 41/41
- 4 min
Final mini task: combine all modules.
Challenge 5 - Cumulative final
The fifth and final challenge combines all previous functions. count_doublings, kmp_search, convex_hull and ford_fulkerson are provided above.
You will write count_matches: given a text and a pattern, find the total number of matches using kmp_search.
This task is the last link of the cumulative chain and the final of the expert level.
Practice count_matches function
Write count_matches(text, pattern). Using kmp_search, return the total number of matches in the text. Print 4 with print(count_matches("abababab", "ab")). The other four functions are provided above.
Starter code
def count_doublings(n):
count = 0
size = 1
last = 0
for i in range(n):
if last == size:
size *= 2
count += 1
last += 1
return count
def kmp_search(text, pattern):
n, m = len(text), len(pattern)
lps = [0] * m
length = 0
i = 1
while i < m:
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
elif length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
i = j = 0
while i < n:
if text[i] == pattern[j]:
i += 1
j += 1
if j == m:
return i - j
elif j != 0:
j = lps[j - 1]
else:
i += 1
return -1
def convex_hull(points):
pts = sorted(set(points))
if len(pts) <= 1:
return pts
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
lower = []
for p in pts:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
upper = []
for p in reversed(pts):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
return lower[:-1] + upper[:-1]
def ford_fulkerson(capacity, source, sink):
from collections import defaultdict
graph = defaultdict(dict)
for u, v, c in capacity:
graph[u][v] = graph[u].get(v, 0) + c
graph[v][u] = graph[v].get(u, 0)
max_flow = 0
def dfs(s, t, flow, visited):
if s == t:
return flow
visited.add(s)
for v in graph[s]:
if v not in visited and graph[s][v] > 0:
pushed = dfs(v, t, min(flow, graph[s][v]), visited)
if pushed > 0:
graph[s][v] -= pushed
graph[v][s] = graph[v].get(s, 0) + pushed
return pushed
return 0
while True:
f = dfs(source, sink, float('inf'), set())
if f == 0:
break
max_flow += f
return max_flow
def count_matches(text, pattern):
# Count all matchesSample solution
def kmp_search(text, pattern):
n, m = len(text), len(pattern)
lps = [0] * m
length = 0
i = 1
while i < m:
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
elif length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
i = j = 0
while i < n:
if text[i] == pattern[j]:
i += 1
j += 1
if j == m:
return i - j
elif j != 0:
j = lps[j - 1]
else:
i += 1
return -1
def count_matches(text, pattern):
total = 0
pos = 0
while pos < len(text):
idx = kmp_search(text[pos:], pattern)
if idx == -1:
break
total += 1
pos += idx + 1
return total
print(count_matches("abababab", "ab"))Expected output
4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 match search
idx = kmp_search(text[____:], pattern)
idx = kmp_search(text[pos:], pattern)
Explanation: Search from pos onward.
2 Which function does count_matches use?
- kmp_search Correct answer
- convex_hull
- ford_fulkerson
- count_doublings
Explanation: count_matches uses kmp_search to count matches.
3 Cumulative chain
| Term | Meaning |
|---|---|
step 1 |
count_doublings |
step 2 |
kmp_search |
step 3 |
convex_hull |
step 4 |
ford_fulkerson |