-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhashtable.py
More file actions
69 lines (56 loc) · 2.05 KB
/
hashtable.py
File metadata and controls
69 lines (56 loc) · 2.05 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
57
58
59
60
61
62
63
64
65
66
67
68
69
"""Contains a HashTable class. The hash table is implemented on a list of
lists, with a default table size of 8192. This table size can be overridden on
initialization by passing a size keyword argument. Insertion and lookup time
complexity ranges from O(1) at best to O(n) at worst.
"""
class HashTable(object):
"""A class for a hash table."""
entries_count = 0
alphabet_size = 52
def __init__(self, size=8192):
self.table_size = size
self.hashtable = [[] for i in range(size)]
def __repr__(self):
return "<HashTable: {}>".format(self.hashtable)
def __len__(self):
count = 0
for item in self.hashtable:
count += len(item)
return count
def _hashing(self, key):
"""Create a hash from a given key.
args:
key: a string to hash
returns: an integer corresponding to hashtable index
"""
hash_ = 0
for i, c in enumerate(key):
hash_ += pow(
self.alphabet_size, len(key) - i - 1) * ord(c)
return hash_ % self.table_size
def set(self, key, value):
"""Add a key and value into the hash table.
args:
key: the key to store
value: the value to store
"""
if not isinstance(key, str):
raise TypeError('Only strings may be used as keys.')
hash_ = self._hashing(key)
for i, item in enumerate(self.hashtable[hash_]):
if item[0] == key:
del self.hashtable[hash_][i]
self.entries_count -= 1
self.hashtable[hash_].append((key, value))
self.entries_count += 1
def get(self, key):
"""Retrieve a value from the hash table by key.
args:
key: a string to find the value in the hash table
returns: the value stored with the key
"""
hash_ = self._hashing(key)
for i, item in enumerate(self.hashtable[hash_]):
if item[0] == key:
return item[1]
raise KeyError('Key not in hash table.')