104 lines
2.2 KiB
Python
104 lines
2.2 KiB
Python
import time
|
|
import random
|
|
import csv
|
|
import sys
|
|
|
|
# 1. LinkedList
|
|
|
|
def ll_insert(head, name, phone):
|
|
|
|
new_node = {'name': name, 'phone': phone, 'next': None}
|
|
|
|
if head is None:
|
|
return new_node
|
|
|
|
if head['name'] == name:
|
|
head['phone'] = phone
|
|
return head
|
|
|
|
current = head
|
|
while current['next'] is not None:
|
|
if current['next']['name'] == name:
|
|
current['next']['phone'] = phone
|
|
return head
|
|
current = current['next']
|
|
|
|
current['next'] = new_node
|
|
return head
|
|
|
|
|
|
def ll_find(head, name):
|
|
|
|
current = head
|
|
while current is not None:
|
|
if current['name'] == name:
|
|
return current['phone']
|
|
current = current['next']
|
|
return None
|
|
|
|
|
|
def ll_delete(head, name):
|
|
|
|
if head is None:
|
|
return None
|
|
|
|
if head['name'] == name:
|
|
return head['next']
|
|
|
|
current = head
|
|
while current['next'] is not None:
|
|
if current['next']['name'] == name:
|
|
current['next'] = current['next']['next']
|
|
return head
|
|
current = current['next']
|
|
|
|
return head
|
|
|
|
|
|
def ll_list_all(head):
|
|
|
|
records = []
|
|
current = head
|
|
while current is not None:
|
|
records.append((current['name'], current['phone']))
|
|
current = current['next']
|
|
records.sort(key=lambda x: x[0])
|
|
return records
|
|
|
|
# 2. Hash Function
|
|
|
|
def hash_function(name, table_size):
|
|
return sum(ord(c) for c in name) % table_size
|
|
|
|
|
|
def ht_create(size=1000):
|
|
return [None] * size
|
|
|
|
|
|
def ht_insert(buckets, name, phone):
|
|
size = len(buckets)
|
|
index = hash_function(name, size)
|
|
buckets[index] = ll_insert(buckets[index], name, phone)
|
|
|
|
|
|
def ht_find(buckets, name):
|
|
size = len(buckets)
|
|
index = hash_function(name, size)
|
|
return ll_find(buckets[index], name)
|
|
|
|
|
|
def ht_delete(buckets, name):
|
|
size = len(buckets)
|
|
index = hash_function(name, size)
|
|
buckets[index] = ll_delete(buckets[index], name)
|
|
|
|
|
|
def ht_list_all(buckets):
|
|
records = []
|
|
for bucket in buckets:
|
|
current = bucket
|
|
while current is not None:
|
|
records.append((current['name'], current['phone']))
|
|
current = current['next']
|
|
records.sort(key=lambda x: x[0])
|
|
return records |