哈希表实现通讯录功能
时间: 2024-03-26 11:30:46 浏览: 142
以下是使用哈希表实现通讯录功能的Python代码:
```python
class Contact:
def __init__(self, name, phone):
self.name = name
self.phone = phone
class HashTable:
def __init__(self, size):
self.size = size
self.table = [[] for _ in range(self.size)]
def _hash_function(self, name):
return sum([ord(c) for c in name]) % self.size
def insert(self, contact):
hash_key = self._hash_function(contact.name)
bucket = self.table[hash_key]
for i, c in enumerate(bucket):
if c.name == contact.name:
bucket[i] = contact
return
bucket.append(contact)
def delete(self, name):
hash_key = self._hash_function(name)
bucket = self.table[hash_key]
for i, c in enumerate(bucket):
if c.name == name:
del bucket[i]
return
def search(self, name):
hash_key = self._hash_function(name)
bucket = self.table[hash_key]
for c in bucket:
if c.name == name:
return c.phone
return None
def menu():
print("1. 添加联系人")
print("2. 删除联系人")
print("3. 查找联系人")
print("4. 退出")
return int(input("请选择操作:"))
if __name__ == '__main__':
contacts = HashTable(10)
while True:
choice = menu()
if choice == 1:
name = input("请输入姓名:")
phone = input("请输入电话号码:")
contact = Contact(name, phone)
contacts.insert(contact)
elif choice == 2:
name = input("请输入要删除的联系人姓名:")
contacts.delete(name)
elif choice == 3:
name = input("请输入要查找的联系人姓名:")
phone = contacts.search(name)
if phone:
print(f"{name}的电话号码是{phone}")
else:
print(f"{name}不存在")
elif choice == 4:
break
else:
print("无效的选择")
```
阅读全文