Skip to content

Instantly share code, notes, and snippets.

@svalleru
Last active March 15, 2016 03:33
Show Gist options
  • Save svalleru/6296f870ddadaae9aec6 to your computer and use it in GitHub Desktop.
Save svalleru/6296f870ddadaae9aec6 to your computer and use it in GitHub Desktop.
Pure python implementation of a dictionary of fixed length
__author__ = 'svalleru'
"""If 'YOU' can't solve it, you can't ask the interviewee to solve it ;)"""
class Dictionary(object):
"""Pure python implementation of a dictionary of fixed length"""
def __init__(self, size):
self.size = size
self.data = [[] for _ in xrange(size)]
#hash method
def _hash(self, key):
return hash(key)%self.size
#insert & update
def __setitem__(self, key, value):
#no hash collision
if len(self.data[self._hash(key)]) == 0:
self.data[self._hash(key)].append([key, value])
#hash collision
else:
#update the value for matching key
for i, kv in enumerate(self.data[self._hash(key)]):
if kv[0] == key:
self.data[self._hash(key)][i][1] = value
return
#no matching key found in the bucket; append
else:
self.data[self._hash(key)].append([key, value])
#retrieve
def __getitem__(self, key):
for i, kv in enumerate(self.data[self._hash(key)]):
if kv[0] == key:
return self.data[self._hash(key)][i][1]
#no matching key found in the bucket
else:
return None
#delete
def __delitem__(self, key):
#only one kv in the bucket
if len(self.data[self._hash(key)]) == 1:
self.data[self._hash(key)].pop(0)
#bucket of len > 1
else:
for i, kv in enumerate(self.data[self._hash(key)]):
if kv[0] == key:
self.data[self._hash(key)].pop(i)
d = Dictionary(10)
d['k1'] = 'v1'
print d['k1']
d['k1'] = 'v1.1'
print d['k1']
d['k2'] = 'v2'
d[9] = 11
print d[9]
d[9] = 12
print d[9]
del d[9]
print d[9]
print d['k2']
del d['k2']
print d['k2']
# Output
# v1
# v1.1
# 11
# 12
# None
# v2
# None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment