def ll_insert(head, name, phone): cur = head while cur: if cur['name'] == name: cur['phone'] = phone return head cur = cur['next'] new_node = {'name': name, 'phone': phone, 'next': None} if head is None: return new_node cur = head while cur['next']: cur = cur['next'] cur['next'] = new_node return head def ll_find(head, name): cur = head while cur: if cur['name'] == name: return cur['phone'] cur = cur['next'] return None def ll_delete(head, name): if head is None: return None if head['name'] == name: return head['next'] prev = head cur = head['next'] while cur: if cur['name'] == name: prev['next'] = cur['next'] return head prev = cur cur = cur['next'] return head def ll_list_all(head): res = [] cur = head while cur: res.append((cur['name'], cur['phone'])) cur = cur['next'] res.sort(key=lambda x: x[0]) return res SIZE = 5 def hash_func(name): s = 0 for ch in name: s += ord(ch) return s % SIZE def ht_insert(buckets, name, phone): idx = hash_func(name) buckets[idx] = ll_insert(buckets[idx], name, phone) return buckets def ht_find(buckets, name): idx = hash_func(name) return ll_find(buckets[idx], name) def ht_delete(buckets, name): idx = hash_func(name) buckets[idx] = ll_delete(buckets[idx], name) return buckets def ht_list_all(buckets): all_rec = [] for head in buckets: cur = head while cur: all_rec.append((cur['name'], cur['phone'])) cur = cur['next'] all_rec.sort(key=lambda x: x[0]) return all_rec if __name__ == '__main__': buckets = [None] * SIZE ht_insert(buckets, '1', '123-456') ht_insert(buckets, '2', '789-012') ht_insert(buckets, '3', '345-678') ht_insert(buckets, '4', '111-222') print("HT all:", ht_list_all(buckets)) print("HT find 1:", ht_find(buckets, '1')) ht_delete(buckets, '2') print("HT after delete 2:", ht_list_all(buckets))