"""So sánh tổng có trọng số với ưu tiên theo thứ tự từ điển.""" from itertools import product LICH = { "A": (0, 9), "B": (1, 2), "C": (2, 0), } def tot_nhat_theo_tong(lich, w): return min(lich, key=lambda ten: w * lich[ten][0] + lich[ten][1]) def tot_nhat_theo_tu_dien(lich): return min(lich, key=lich.get) if __name__ == "__main__": assert tot_nhat_theo_tu_dien(LICH) == "A" for w in (1, 5, 7, 8, 10): scores = {ten: w * p + q for ten, (p, q) in LICH.items()} print(f"w={w:2}: {scores}; chọn {tot_nhat_theo_tong(LICH, w)}") # w=7 làm A và B hòa. w=8 đủ để tách ba lịch đã biết. assert 7 * LICH["A"][0] + LICH["A"][1] == 7 * LICH["B"][0] + LICH["B"][1] assert tot_nhat_theo_tong(LICH, 5) == "B" assert tot_nhat_theo_tong(LICH, 8) == "A" # Chứng thực bằng liệt kê cho toàn miền 0 <= Q <= 9. # Khi P cải thiện ít nhất một đơn vị, w=10 luôn giữ ưu tiên. pairs = list(product(range(3), range(10))) assert sorted(pairs) == sorted(pairs, key=lambda pair: 10 * pair[0] + pair[1])