验证列表与集合、字典的计算效率 ·构建分别包含一千条、一万和十万条数据的数据源:电话本(由姓名 和电话号构成) 编写程序,分别查找其中任意名字或标识符的电话号码。给我完整的可执行的python代码 能不能看懂要求,按这个要求给我代码
时间: 2024-09-09 16:14:31 浏览: 45
当然,我可以帮你编写一个简单的Python代码,用于演示在电话本中查找名字或电话号码的速度差异。我们将使用列表(List)、集合(Set)和字典(Dictionary)这三种数据结构,并为每个数据结构创建不同规模的实例。这里我们假设电话本是一个字典,键是名字或电话号码,值是对应的另一个键。
```python
import time
# 定义电话本数据结构和大小
data_sizes = [1000, 10000, 100000]
structures = ['list', 'set', 'dictionary']
phone_book_list = []
phone_book_set = set()
phone_book_dict = {}
# 填充数据
for size in data_sizes:
for i in range(size):
name = f"name_{i}"
phone_number = f"phone_{i}"
# 对于列表,添加元组
phone_book_list.append((name, phone_number))
# 对于集合,只存储电话号码
phone_book_set.add(phone_number)
# 对于字典,先将姓名映射到电话号码,然后反向映射
phone_book_dict[name] = phone_number
phone_book_dict[phone_number] = name
# 测试查找速度
results = {}
for structure in structures:
for size in data_sizes:
test_name = "test_name"
test_phone = "test_phone"
start_time = time.time()
if structure == 'list':
found = [(item, phone_book_list.index(item)) for item in phone_book_list if item[0] == test_name or item[1] == test_phone]
elif structure == 'set':
found = [phone for phone in phone_book_set if str(test_name) in phone or str(test_phone) in phone]
else: # dictionary
found = [phone_book_dict.get(key) for key in [test_name, test_phone]]
end_time = time.time()
execution_time = end_time - start_time
results[f"{structure}_{size}"] = {"time": execution_time, "result": found}
print("\nComparison of search times:")
for data, details in results.items():
print(f"{data}: Time taken to search: {details['time']} seconds, Results: {details['result']}")
阅读全文