diff --git a/KuznetsovYuM/docs/data/1-st-exercise/phonebook_structures.py b/KuznetsovYuM/docs/data/1-st-exercise/phonebook_structures.py index 25b9bf4..e16a070 100644 --- a/KuznetsovYuM/docs/data/1-st-exercise/phonebook_structures.py +++ b/KuznetsovYuM/docs/data/1-st-exercise/phonebook_structures.py @@ -1,4 +1,3 @@ - def linked_list_add(head, name, phone): curr = head while curr is not None: @@ -30,10 +29,8 @@ def linked_list_find(head, name): def linked_list_remove(head, name): if head is None: return None - if head['name'] == name: return head['next'] - prev = head curr = head['next'] while curr is not None: @@ -55,13 +52,49 @@ def linked_list_collect_all(head): return records -# Quick test +def _hash_bucket_index(key, table_size): + return hash(key) % table_size + + +def hash_table_create(bucket_count=10): + return [None] * bucket_count + + +def hash_table_put(table, name, phone): + idx = _hash_bucket_index(name, len(table)) + table[idx] = linked_list_add(table[idx], name, phone) + return table + + +def hash_table_get(table, name): + idx = _hash_bucket_index(name, len(table)) + return linked_list_find(table[idx], name) + + +def hash_table_remove(table, name): + idx = _hash_bucket_index(name, len(table)) + table[idx] = linked_list_remove(table[idx], name) + return table + + +def hash_table_collect_all(table): + all_records = [] + for head in table: + curr = head + while curr is not None: + all_records.append((curr['name'], curr['phone'])) + curr = curr['next'] + all_records.sort(key=lambda pair: pair[0]) + return all_records + + +# Quick test if __name__ == '__main__': - lst = None - lst = linked_list_add(lst, 'Alice', '111-222') - lst = linked_list_add(lst, 'Bob', '333-444') - lst = linked_list_add(lst, 'Alice', '555-666') - print(linked_list_find(lst, 'Alice')) # 555-666 - print(linked_list_collect_all(lst)) # [('Alice','555-666'), ('Bob','333-444')] - lst = linked_list_remove(lst, 'Bob') - print(linked_list_collect_all(lst)) # [('Alice','555-666')] \ No newline at end of file + ht = hash_table_create(5) + ht = hash_table_put(ht, 'Alice', '111') + ht = hash_table_put(ht, 'Bob', '222') + ht = hash_table_put(ht, 'Alice', '333') + print(hash_table_get(ht, 'Alice')) # 333 + print(hash_table_get(ht, 'Charlie')) # None + ht = hash_table_remove(ht, 'Bob') + print(hash_table_collect_all(ht)) # [('Alice','333')] \ No newline at end of file