-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_keys.py
49 lines (40 loc) · 1.31 KB
/
string_keys.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
class HashTable(object):
def __init__(self):
self.table = [None] * 10000
def store(self, string):
"""Input a string that's stored in
the table."""
hash_value = self.calculate_hash_value(string)
if self.table[hash_value]:
self.table[hash_value].append(string)
else:
self.table[hash_value] = [string]
def lookup(self, string):
"""Return the hash value if the
string is already in the table.
Return -1 otherwise."""
hash_value = self.calculate_hash_value(string)
stored = self.table[hash_value]
if stored and string in stored:
return hash_value
return -1
def calculate_hash_value(self, string):
"""Helper function to calulate a
hash value from a string."""
return ord(string[0]) * 100 + ord(string[1])
# Setup
hash_table = HashTable()
# Test calculate_hash_value
# Should be 8568
print (hash_table.calculate_hash_value('UDACITY'))
# Test lookup edge case
# Should be -1
print (hash_table.lookup('UDACITY'))
# Test store
hash_table.store('UDACITY')
# Should be 8568
print(hash_table.lookup('UDACITY'))
# Test store edge case
hash_table.store('UDACIOUS')
# Should be 8568
print(hash_table.lookup('UDACIOUS'))