[6] add hash func find, insert and hash_func
This commit is contained in:
parent
0e84534109
commit
e868e94fcd
|
|
@ -120,55 +120,40 @@ print("====== END ======")
|
|||
|
||||
|
||||
|
||||
# 2.hash tables
|
||||
|
||||
|
||||
SIZE = 1000
|
||||
SIZE = 5
|
||||
buckets = [None] * SIZE
|
||||
|
||||
def hash_func(name):
|
||||
return hash(name) % SIZE
|
||||
|
||||
|
||||
def hash_function(name, size):
|
||||
return hash(name) % size
|
||||
|
||||
|
||||
def ht_insert(buckets, name, phone):
|
||||
idx = hash_func(name)
|
||||
buckets[idx] = ll_insert(buckets[idx], name, phone)
|
||||
return buckets
|
||||
index = hash_function(name, len(buckets))
|
||||
head = buckets[index]
|
||||
new_head = ll_insert(head, name, phone)
|
||||
buckets[index] = new_head
|
||||
|
||||
print(f"\n\n\n ====== TEST INSERT HASH ======")
|
||||
print(buckets)
|
||||
ht_insert(buckets, "Ivan", "123-456")
|
||||
print(buckets)
|
||||
ht_insert(buckets, "Dima", "789-123")
|
||||
print(buckets)
|
||||
ht_insert(buckets, "Boris", "456-789")
|
||||
print(buckets)
|
||||
print("====== END TEST ======\n\n\n")
|
||||
|
||||
|
||||
def ht_find(buckets, name):
|
||||
idx = hash_func(name)
|
||||
return ll_find(buckets[idx], name)
|
||||
index = hash_function(name, len(buckets))
|
||||
head = buckets[index]
|
||||
return ll_find(head, name)
|
||||
|
||||
print("====== TEST FIND HASH FUN ======")
|
||||
print("find by name Ivan: ",ht_find(buckets, "Ivan"))
|
||||
print("find by name Dima: ",ht_find(buckets, "Dima"))
|
||||
print("find by name Boris: ", ht_find(buckets, "Boris"))
|
||||
print("====== END TEST ======")
|
||||
|
||||
def ht_delete(buckets, name):
|
||||
idx = hash_func(name)
|
||||
buckets[idx] = ll_delete(buckets[idx], name)
|
||||
return buckets
|
||||
|
||||
def ht_list_all(buckets):
|
||||
all_records = []
|
||||
for head in buckets:
|
||||
current = head
|
||||
while current is not None:
|
||||
all_records.append((current['name'], current['phone']))
|
||||
current = current['next']
|
||||
all_records.sort(key=lambda pair: pair[0])
|
||||
return all_records
|
||||
|
||||
|
||||
|
||||
print("---- TESTING BUCKETS ----")
|
||||
|
||||
buckets = ht_insert(buckets, 'Alice', '111-111')
|
||||
buckets = ht_insert(buckets, 'Bob', '222-222')
|
||||
buckets = ht_insert(buckets, 'Charlie', '333-333')
|
||||
buckets = ht_insert(buckets, 'Alice', '999-999')
|
||||
|
||||
print(ht_find(buckets, 'Bob'))
|
||||
|
||||
print(ht_find(buckets, 'David'))
|
||||
|
||||
buckets = ht_delete(buckets, 'Bob')
|
||||
|
||||
print(ht_find(buckets, 'Bob'))
|
||||
|
||||
print(ht_list_all(buckets))
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user