-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q05_sparse_search.py
80 lines (66 loc) · 2.42 KB
/
Q05_sparse_search.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import unittest
def sparse_search(strings, target):
left = 0
right = len(strings) - 1
return binary_search(left, right, strings, target)
def binary_search(left, right, strings, target):
if left > right:
return -1
mid = left + ((right - left) // 2)
if strings[mid] == target:
return mid
elif strings[mid] == "":
upper = mid + 1
while upper <= right:
if strings[upper] != "":
if strings[upper] == target:
return upper
elif strings[upper] > target:
return binary_search(left, mid - 1, strings, target)
elif strings[upper] < target:
return binary_search(upper + 1, right, strings, target)
upper += 1
lower = mid - 1
while lower >= left:
if strings[lower] != "":
if strings[lower] == target:
return lower
elif strings[lower] > target:
return binary_search(left, lower - 1, strings, target)
elif strings[upper] < target:
return binary_search(mid + 1, right, strings, target)
lower -= 1
elif strings[mid] > target:
return binary_search(left, mid - 1, strings, target)
elif strings[mid] < target:
return binary_search(mid + 1, right, strings, target)
return -1
class Test(unittest.TestCase):
def test_power_of_two(self):
self.assertEqual(
3, sparse_search(["at", "", "", "ball", "", "", "", "cat"], "ball")
)
self.assertEqual(
1, sparse_search(["at", "ball", "", "", "", "", "", ""], "ball")
)
self.assertEqual(
0, sparse_search(["at", "", "back", "", "ball", "", "", "cat"], "at")
)
self.assertEqual(
7, sparse_search(["at", "", "", "", "ball", "", "", "cat"], "cat")
)
self.assertEqual(
-1, sparse_search(["at", "", "", "", "ball", "", "", "cat"], "hat")
)
self.assertEqual(
-1, sparse_search(["at", "", "back", "", "ball", "", "", ""], "hat")
)
self.assertEqual(
-1, sparse_search(["", "", "back", "", "ball", "", "", ""], "at")
)
self.assertEqual(
6,
sparse_search(
["at", "bat", "cat", "gate", "mate", "pat", "sat", "yak"], "sat"
),
)