题目

综合设计题:设计一个简易命令行通讯录系统,支持联系人的添加(姓名、电话)、按姓名查找以及删除功能。

输入格式:多行交互指令:1 姓名 电话 添加联系人;2 姓名 查找联系人;3 姓名 删除联系人;0 退出系统。

输出格式:查找成功输出 姓名 电话,未找到输出 not found。

数据范围与约定:通讯录容量上限为 20 条记录。

思路与算法

1. 记录存储结构
使用元组列表 book = [] 或对象管理联系人记录。

2. 查找与删除
遍历匹配姓名进行查询;删除时利用列表移动或覆盖操作完成记录维护。

完整程序

import sys

# 简易通讯录系统
book = []
tokens = sys.stdin.read().split()
idx = 0

while idx < len(tokens):
    cmd = int(tokens[idx])
    idx += 1
    if cmd == 0:
        # 退出系统
        break
    if cmd == 1 and len(book) < 20:
        # 添加联系人
        name = tokens[idx]
        phone = tokens[idx + 1]
        idx += 2
        book.append((name, phone))
    elif cmd == 2:
        # 查找联系人
        key = tokens[idx]
        idx += 1
        found = next(((n, p) for n, p in book if n == key), None)
        print(f'{found[0]} {found[1]}' if found else 'not found')
    elif cmd == 3:
        # 删除联系人:将末尾覆盖到被删位置
        key = tokens[idx]
        idx += 1
        for i, (n, p) in enumerate(book):
            if n == key:
                book[i] = book[-1]
                book.pop()
                break

运行示例

输入:

1 Amy 10001
2 Amy
3 Amy
0

输出:

Amy 10001
not found