class Node:
def __init__(self, name, phone, address, next):
self._name = name
self._phone = phone
self._address = address
self._next = next
def __str__(self):
return "("+self._name+","+self._phone+","+self._address+")"
class ContactsHT:
MAXSIZE = 100
def __init__(self):
self._hashtable = [Node("","","",None) for i in range(ContactsHT.MAXSIZE)]
self._size = 0
@classmethod
def myhash(cls,name):
sum = 0
for x in name:
sum = sum + ord(x)
return sum%ContactsHT.MAXSIZE
def find(self,name):
# Return pointer to previous node if found
# Return None if not found
hindex = ContactsHT.myhash(name)
p = self._hashtable[hindex]
found = False
while p._next != None and not found:
if p._next._name == name:
found = True
else:
p = p._next
if found:
return p
else:
None
def insert(self,contact):
# insert contact as 1st item in linked list because we are not maintaining
# sorted entries
# first check if name is already in list; if yes the do not insert
p = self.find(contact[0])
if p == None:
hindex = ContactsHT.myhash(contact[0])
n = Node(contact[0],contact[1],contact[2],self._hashtable[hindex]._next)
self._hashtable[hindex]._next = n
self._size = self._size + 1
return True
else:
return False
def delete(self,name):
p = self.find(name)
if p == None:
return False
else:
p._next = p._next._next
self._size = self._size - 1
return True
def size(self):
return self._size
def update(self,contact):
p = self.find(contact[0])
if p == None:
return False
else:
p._next._phone = contact[1]
p._next._address = contact[2]
return True
def __str__(self):
result = "\n"
for hindex in range(ContactsHT.MAXSIZE):
p = self._hashtable[hindex]
while p._next != None:
result = result + str(p._next)+"\n"
p = p._next
return result + "\n"
mylist = ContactsHT()
mylist.insert(("Alice","111-1111","123 Main Street"))
mylist.insert(("James","111-1112","123 Elm Street"))
mylist.insert(("John","111-1113","123 Oak Street"))
mylist.update(("Alice","999-9999","123 Oak Street"))
mylist.delete("James")
x = mylist.insert(("Alice","888-8888","123 Main Street"))
print(x)
x = mylist.delete("Raj")
print(x)
print(mylist)