Python实现:找出卡路里最高的Elf并打印其编号而非数值
解决Advent of Code问题:关联最高卡路里与对应Elf编号
问题分析
你当前的代码能计算出每个Elf的总卡路里并找到最大值,但因为没有将Elf编号和总卡路里绑定存储,导致无法直接关联两者。另外最后一行打印代码还存在类型错误(整数与字符串不能直接拼接)。
优化方案(简化代码+关联编号)
用循环替代重复的变量定义,同时将Elf编号和总卡路里以元组形式存储,确保两者始终关联:
# 设定Elf数量 elf_count = 5 # 存储(Elf编号, 总卡路里)的列表 elf_calorie_totals = [] for elf_num in range(1, elf_count + 1): # 输入当前Elf的物品卡路里(空格分隔) input_content = input(f"insert item calories of elf {elf_num}(separated by space):") # 将输入字符串转为整数列表并计算总卡路里 calorie_list = list(map(int, input_content.split())) total_calories = sum(calorie_list) # 存入编号与总卡路里的关联数据 elf_calorie_totals.append( (elf_num, total_calories) ) # 找到总卡路里最高的Elf(按元组第二个元素比较) top_elf = max(elf_calorie_totals, key=lambda item: item[1]) # 格式化输出结果 print(f"卡路里最高的Elf是:Elf no{top_elf[0]}")
针对原代码的最小修改
如果不想改动原有输入和计算逻辑,只需调整最后关联编号的部分:
# 原代码中计算完total_1到total_5后,替换以下代码: # 存储编号与对应总卡路里的元组列表 calorie_table = [ (1, total_1), (2, total_2), (3, total_3), (4, total_4), (5, total_5) ] # 找到最高卡路里对应的Elf highest_elf = max(calorie_table, key=lambda x: x[1]) # 输出结果(用f-string避免类型错误) print(f"卡路里最高的Elf是:Elf no{highest_elf[0]}")
关键说明
- 用元组/字典存储关联数据,是解决“值与对应标识绑定”问题的常用方法
max()函数的key参数用于指定比较的依据(这里是总卡路里值)- f-string是Python中格式化字符串的简洁方式,同时避免了整数与字符串拼接的类型错误
内容的提问来源于stack exchange,提问作者Gonçalo Rocha
相关产品推荐
相关产品推荐

