Build a tiny dictionary: a hash function picks a bucket for each key. "cat" and "act" land in the same bucket: a collision.
Python · intermediate · 8 min · 37 steps · free
class HashTable:
def __init__(self):
self.buckets = [[], [], [], []]
def index(self, key):
return sum(map(ord, key)) % len(self.buckets)
def put(self, key, value):
bucket = self.buckets[self.index(key)]
bucket.append([key, value])
def get(self, key):
for pair in self.buckets[self.index(key)]:
if pair[0] == key:
return pair[1]
return None
table = HashTable()
table.put('cat', 3)
table.put('dog', 1)
table.put('act', 5)
print(table.get('act'))HashTable. Its methods are stored, but none of them run yet.class HashTable belongs to it.__init__ is stored in HashTable. It runs only when it is called on an object.index is stored in HashTable. It runs only when it is called on an object.put is stored in HashTable. It runs only when it is called on an object.get is stored in HashTable. It runs only when it is called on an object.HashTable is now defined, ready to make objects from.__init__(), with self = {}. It gets its own names.buckets with the value a list is added to the HashTable that self points to.__init__() has finished, so its names are gone. The value it returned, {buckets: a list}, is stored in table.put(), with self = {buckets: a list}, key = 'cat' and value = 3. It gets its own names.index(), with self = {buckets: a list} and key = 'cat'. It gets its own names.index() has finished, so its names are gone. The value it returned, [], is stored in bucket.put() has finished, so its names are gone.put(), with self = {buckets: a list}, key = 'dog' and value = 1. It gets its own names.index(), with self = {buckets: a list} and key = 'dog'. It gets its own names.sum(map(ord, key)) % len(self.buckets).index() has finished, so its names are gone. The value it returned, [], is stored in bucket.bucket points to.put() has finished, so its names are gone.put(), with self = {buckets: a list}, key = 'act' and value = 5. It gets its own names.index(), with self = {buckets: a list} and key = 'act'. It gets its own names.sum(map(ord, key)) % len(self.buckets).index() has finished, so its names are gone. The value it returned, [a list], is stored in bucket.put() has finished, so its names are gone.get(), with self = {buckets: a list} and key = 'act'. It gets its own names.index(), with self = {buckets: a list} and key = 'act'. It gets its own names.sum(map(ord, key)) % len(self.buckets).index() has finished, so its names are gone. The value it returned, ['cat', 3], is stored in pair.pair[0] == key is false, so the block under it is skipped.pair now points to a different list: ['act', 5].pair[1].get() has finished, so its names are gone. It prints 5.Answer: They can change, so their hash would change
Answer: O(1)
← Queues · Two Sum with a Hash Map →