Bài tập List & Dictionary
Chủ đề:
list,dict,tuple,set, các thao tác CRUD, list comprehension.
Phần 1 – Trắc Nghiệm
Câu 1. Kết quả của [1, 2, 3, 4, 5][1:4] là gì?
- A.
[1, 2, 3] - B.
[2, 3, 4] - C.
[2, 3, 4, 5] - D.
[1, 2, 3, 4]
Câu 2. Cách nào thêm phần tử vào cuối list?
- A.
lst.insert(0, x) - B.
lst.add(x) - C.
lst.append(x) - D.
lst.push(x)
Câu 3. dict.get("key", "default") trả về gì nếu "key" không tồn tại?
- A.
None - B.
KeyError - C.
"default" - D.
False
Phần 2 – Điền Khuyết
Bài 1. Dùng list comprehension để tạo danh sách bình phương từ 1–10:
binh_phuong = [x ___ for x in range(1, 11)]
print(binh_phuong) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Đáp án
binh_phuong = [x ** 2 for x in range(1, 11)]
Phần 3 – Lập Trình Thực Hành
Bài 1 – Quản lý danh sách học sinh
Viết trình:
- Nhập danh sách tên học sinh
- Sắp xếp theo bảng chữ cái
- Tìm kiếm học sinh theo tên
- Xóa học sinh khỏi danh sách
Đáp án mẫu
hoc_sinh = []
def them(ten):
hoc_sinh.append(ten)
print(f" Đã thêm: {ten}")
def hien_thi():
if not hoc_sinh:
print("Danh sách trống!")
else:
for i, ten in enumerate(sorted(hoc_sinh), 1):
print(f" {i}. {ten}")
def tim_kiem(ten):
return ten in hoc_sinh
def xoa(ten):
if ten in hoc_sinh:
hoc_sinh.remove(ten)
print(f" Đã xóa: {ten}")
else:
print(f" Không tìm thấy: {ten}")
# Thử nghiệm
them("Nguyễn Văn A")
them("Trần Thị B")
them("Lê Văn C")
hien_thi()
print(f"Tìm 'Trần Thị B': {tim_kiem('Trần Thị B')}")
xoa("Trần Thị B")
hien_thi()
Bài 2 – Thống kê điểm số
Nhập danh sách điểm số, tính: min, max, trung bình, trung vị và đếm số học sinh đạt/rớt.
Đáp án mẫu
import statistics
n = int(input("Số học sinh: "))
diem = [float(input(f" Điểm học sinh {i+1}: ")) for i in range(n)]
print(f"\n Thống kê điểm:")
print(f" Min : {min(diem)}")
print(f" Max : {max(diem)}")
print(f" TB : {sum(diem)/len(diem):.2f}")
print(f" Trung vị: {statistics.median(diem)}")
print(f" Đạt (≥5): {sum(1 for d in diem if d >= 5)} học sinh")
print(f" Rớt (<5): {sum(1 for d in diem if d < 5)} học sinh")
Bài 3 – Đếm tần suất từ
Nhập một đoạn văn bản, đếm số lần xuất hiện của mỗi từ và in ra các từ xuất hiện nhiều nhất.
Đáp án mẫu
van_ban = input("Nhập đoạn văn: ").lower()
tu_list = van_ban.split()
tan_suat = {}
for tu in tu_list:
tan_suat[tu] = tan_suat.get(tu, 0) + 1
# Sắp xếp giảm dần theo tần suất
sap_xep = sorted(tan_suat.items(), key=lambda x: x[1], reverse=True)
print("\n Tần suất từ:")
for tu, so_lan in sap_xep[:10]: # Top 10
print(f" '{tu}': {so_lan} lần")
Bài 4 – Sổ liên lạc
Xây dựng sổ liên lạc bằng dictionary với các chức năng: thêm, xem, tìm kiếm, xóa liên lạc.
Đáp án mẫu
so_lien_lac = {}
def them_lien_lac(ten, sdt, email=""):
so_lien_lac[ten] = {"SĐT": sdt, "Email": email}
print(f" Đã thêm: {ten}")
def xem_tat_ca():
if not so_lien_lac:
print("Sổ liên lạc trống!")
return
print("\n Sổ liên lạc:")
for ten, info in sorted(so_lien_lac.items()):
print(f" {ten}")
print(f" SĐT : {info['SĐT']}")
if info['Email']:
print(f" Email: {info['Email']}")
def tim_kiem(ten):
if ten in so_lien_lac:
info = so_lien_lac[ten]
print(f" Tìm thấy: {ten} — SĐT: {info['SĐT']}")
else:
print(f" Không tìm thấy: {ten}")
def xoa_lien_lac(ten):
if ten in so_lien_lac:
del so_lien_lac[ten]
print(f" Đã xóa: {ten}")
else:
print(f" Không tìm thấy: {ten}")
# Thử nghiệm
them_lien_lac("Nguyễn Thanh Vũ", "0901234567", "vu@email.com")
them_lien_lac("Trần Thị Lan", "0987654321")
xem_tat_ca()
tim_kiem("Nguyễn Thanh Vũ")
xoa_lien_lac("Trần Thị Lan")
xem_tat_ca()
Tiếp theo: 6 – Lập Trình Hướng Đối Tượng