[1] add hash tabel
This commit is contained in:
parent
678e6f2c07
commit
c4a7d2a1bf
|
|
@ -46,14 +46,45 @@ def ll_list_all(head):
|
|||
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__':
|
||||
head = None
|
||||
head = ll_insert(head, 'Pasha', '123-456')
|
||||
head = ll_insert(head, 'Andrey', '789-012')
|
||||
head = ll_insert(head, 'Alisa', '345-678')
|
||||
head = ll_insert(head, 'Anna', '111-222')
|
||||
print("All:", ll_list_all(head))
|
||||
print("Find Pasha:", ll_find(head, 'Pasha'))
|
||||
head = ll_delete(head, 'Andrey')
|
||||
print("After delete Andrey:", ll_list_all(head))
|
||||
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))
|
||||
Loading…
Reference in New Issue
Block a user