Skip to content

Commit 545f222

Browse files
committed
add binary_search_st
1 parent 2cdfd5c commit 545f222

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed

algs4/binary_search_st.py

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
"""
2+
* Execution: python binary_search_st
3+
* Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt
4+
*
5+
* Symbol table implementation with binary search in an ordered array.
6+
*
7+
* % more tinyST.txt
8+
* S E A R C H E X A M P L E
9+
*
10+
* % python binary_search_st < tinyST.txt
11+
* C 4
12+
* E 12
13+
* H 5
14+
* L 11
15+
* M 9
16+
* P 10
17+
* R 3
18+
* S 0
19+
* X 7
20+
*
21+
"""
22+
23+
24+
class BinarySearchST:
25+
init_capacity = 2
26+
27+
def __init__(self):
28+
self.keys = [None]*self.init_capacity
29+
self.vals = [None]*self.init_capacity
30+
self.n = 0
31+
32+
def rank(self, arr, key):
33+
lo, hi = 0, self.n - 1
34+
while lo <= hi:
35+
mid = lo + (hi - lo) // 2
36+
if (key < arr[mid]):
37+
hi = mid - 1
38+
elif (key > arr[mid]):
39+
lo = mid + 1
40+
else:
41+
return mid
42+
return lo
43+
44+
def resize(self, capacity):
45+
self.keys = self.keys + [None]*(capacity-len(self.keys))
46+
self.vals = self.vals + [None]*(capacity-len(self.vals))
47+
48+
def contains(self, key):
49+
return self.get(key) != None
50+
51+
def get(self, key):
52+
i = self.rank(self.keys, key)
53+
if i < self.n and self.keys[i] == key:
54+
return self.vals[i]
55+
return None
56+
57+
def put(self, key, val):
58+
i = self.rank(self.keys, key)
59+
if i < self.n and self.keys[i] == key:
60+
self.vals[i] = val
61+
return
62+
63+
if self.n == len(self.keys):
64+
self.resize(self.n*2)
65+
66+
j = self.n
67+
while j > i:
68+
self.keys[j], self.vals[j] = self.keys[j-1], self.vals[j-1]
69+
j -= 1
70+
self.keys[i], self.vals[i] = key, val
71+
self.n += 1
72+
73+
def delete(self, key):
74+
self.put(key, None)
75+
76+
def is_empty(self):
77+
return self.n == 0
78+
79+
def Size(self):
80+
return self.n
81+
82+
def Keys(self):
83+
return self.keys[:self.n]
84+
85+
86+
if __name__ == '__main__':
87+
import sys
88+
st = BinarySearchST()
89+
i = 0
90+
for line in sys.stdin:
91+
for key in line.split():
92+
st.put(key, i)
93+
i += 1
94+
for s in st.Keys():
95+
print(s + " " + str(st.get(s)))

0 commit comments

Comments
 (0)