class Node():
def __init__(self,n,p,a,x):
self.name = n
self.phone = p
self.address = a
self.next = x
def __str__(self):
return "(" + self.name + "," + self.phone + "," + self.address + ")"
class ContactsHT():
MAXSIZE = 100 # number of buckets
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 # RAJ and JAR will map to same bucket
def find(self,n):
bno = ContactsHT.myhash(n)
p = self.hashtable[bno]
found = False
while (p.next != None) and not found:
if p.next.name == n:
found = True
else:
p = p.next
if found:
return p
else:
return None
def insert(self,n,p,a):
position = self.find(n)
if position == None:
bno = ContactsHT.myhash(n)
print(n,"goes into bucket",bno)
position = self.hashtable[bno]
node = Node(n,p,a,position.next)
position.next = node
self.size = self.size + 1
return True
else:
return False
def delete(self,n):
position = self.find(n)
if position != None:
position.next = position.next.next
self.size = self.size - 1
return True
else:
return False
def update(self,n,p,a):
position = self.find(n)
if position != None:
position.next.phone = p
position.next.address = a
return True
else:
return False
def __str__(self):
result = "**********\n"
for bno in range(ContactsHT.MAXSIZE):
p = self.hashtable[bno]
while p.next != None:
result = result + str(p.next) + "\n"
p = p.next
return result + "**********\n"
contacts = ContactsHT()
contacts.insert("John","111","123 main street")
print(contacts)
contacts.insert("Alice","112","124 main street")
print(contacts)
contacts.insert("Beth","113","125 main street")
print(contacts)
contacts.insert("theB","113","125 main street")
print(contacts)
John goes into bucket 99 ********** (John,111,123 main street) ********** Alice goes into bucket 78 ********** (Alice,112,124 main street) (John,111,123 main street) ********** Beth goes into bucket 87 ********** (Alice,112,124 main street) (Beth,113,125 main street) (John,111,123 main street) ********** theB goes into bucket 87 ********** (Alice,112,124 main street) (theB,113,125 main street) (Beth,113,125 main street) (John,111,123 main street) **********
[5 for i in range(2,11,2)]
[5, 5, 5, 5, 5]