-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc-13.16.py
40 lines (32 loc) · 849 Bytes
/
c-13.16.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""
Adapt the brute-force pattern-matching algorithm in order to implement a function
rfind_brute(T, P), that returns the index at which the rightmost occurrence of pattern P
within the text T, if any.
"""
def find_brute(T, P):
n, m = len(T), len(P)
for i in range(n-m+1):
k = 0
while k < m and T[i + k] == P[k]:
k += 1
if k == m:
return i
return -1
def rfind_brute(T, P):
n, m = len(T), len(P)
for i in range(n, m-1, -1):
k = 0
while k < m and T[i-m + k] == P[k]:
k += 1
if k == m:
return i-m
return -1
if __name__ == "__main__":
T = 'ababaaa'
P = 'ba'
assert find_brute(T, P) == 1
assert rfind_brute(T, P) == 3
T = ''
P = 'a'
assert find_brute(T, P) == -1
assert rfind_brute(T, P) == -1