-
Notifications
You must be signed in to change notification settings - Fork 77
/
sequential_search_st.py
92 lines (77 loc) · 1.85 KB
/
sequential_search_st.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
80
81
82
83
84
85
86
87
88
89
90
91
92
"""
* Execution: python3 sequential_search_st.py
* Data files: https://algs4.cs.princeton.edu/31elementary/tinyST.txt
*
* Symbol table implementation with sequential search in an
* unordered linked list of key-value pairs.
*
* % more tinyST.txt
* S E A R C H E X A M P L E
*
* % python3 sequential_search_st.py < tinyST.txt
* L 11
* P 10
* M 9
* X 7
* H 5
* C 4
* R 3
* A 8
* E 12
* S 0
*
"""
from algs4.utils.st import Node, STKeyIterator
class SequentialSearchST:
def __init__(self):
self.first = None
self.size = 0
def contains(self, key):
x = self.first
while x:
if key == x.key:
return True
x = x.next
return False
def get(self, key):
x = self.first
while x:
if key == x.key:
return x.val
x = x.next
return None
def put(self, key, val):
x = self.first
while x:
if key == x.key:
x.val = val
return
x = x.next
self.first = Node(key, val, self.first)
self.size += 1
def delete(self, key):
prev = None
curr = self.first
while curr:
if key == curr.key:
if prev:
prev.next = curr.next
else:
self.first = curr.ext
self.size -= 1
prev = curr
curr = curr.next
def Keys(self):
return STKeyIterator(self.first)
def is_empty(self):
return self.size == 0
if __name__ == '__main__':
import sys
st = SequentialSearchST()
i = 0
for line in sys.stdin:
for key in line.split():
st.put(key, i)
i += 1
for key in st.Keys():
print(key + " " + str(st.get(key)))