Python实现AdventOfCode2021第3天第2部分时列表剩2元素remove不生效
问题原因
你的代码核心问题是循环内的执行顺序错误:
- 你将「列表长度是否为1」的判断放在了每轮过滤操作之前,当处理最后一位索引(idx=4)时,进入循环时列表长度为2,不触发终止判断,过滤后列表仅剩
['10111'],但此时所有索引已经遍历完毕,循环直接结束,o2_code没有被赋值,你看到的打印结果都是每轮过滤前的列表状态,过滤后的最终结果没有被打印。 - 你用返回
'-1'再取最后一位获取持平场景保留值的写法可读性较差,容易出现隐性错误。
修复方案
调整循环逻辑,要么把长度判断放在过滤操作之后,要么在循环结束后直接取列表的唯一元素作为结果,同时简化持平场景的返回逻辑:
from collections import Counter def most_common_at_idx(idx, lst): idx_lst = [item[idx] for item in lst] data = Counter(idx_lst) two_most_common = data.most_common(2) # 计数持平直接返回规则要求的1,否则返回出现频次更高的字符 if len(two_most_common) == 2 and two_most_common[0][1] == two_most_common[1][1]: return '1' return two_most_common[0][0] sample = [ "00100", "11110", "10110", "10111", "10101", "01111", "00111", "11100", "10000", "11001", "00010", "01010" ] power_input = sample o2_rating = power_input.copy() for idx in range(len(power_input[0])): if len(o2_rating) == 1: break char = most_common_at_idx(idx, o2_rating) o2_rating = [item for item in o2_rating if item[idx] == char] o2_code = o2_rating[0] print(o2_code) # 输出10111,符合预期
内容的提问来源于stack exchange,提问作者G-BC
相关产品推荐
相关产品推荐

