-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkey string.py
More file actions
56 lines (43 loc) · 1.41 KB
/
Copy pathkey string.py
File metadata and controls
56 lines (43 loc) · 1.41 KB
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
class HashTable(object):
def __init__(self):
self.table = [None]*10000
def store(self, string):
hashValue=self.calculate_hash_value(string)
if hashValue != -1:
if self.table[hashValue] != None:
self.table[hashValue].append(string)
else:
self.table[hashValue] = [string]
"""Input a string that's stored in
the table."""
def lookup(self, string):
hashValue=self.calculate_hash_value(string)
if hashValue!=-1:
if self.table[hashValue]!=None:
if string in self.table[hashValue]:
return hashValue
return -1
"""Return the hash value if the
string is already in the table.
Return -1 otherwise."""
def calculate_hash_value(self, string):
"""Helper function to calulate a
hash value from a string."""
hashValue=ord(string[0])*100+ord(string[1])
return hashValue
# 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')