Advent of Code第1天第2部分代码无输出无报错求助
问题分析与修复
你的代码运行无输出无报错,核心问题出在几个细节错误上:
主要错误点
isdigit未加括号调用:input[0:1].isdigit是引用方法对象而非调用方法,永远返回True(非空对象布尔值为真),导致阿拉伯数字的判断逻辑完全失效,必须改成input[0:1].isdigit()。- 反向查找函数的数字判断逻辑错误:
isnumberspelledbackwards函数里,判断阿拉伯数字时错误地检查字符串开头(input[0:1]),但这个函数的目标是找最后一个数字,应该检查字符串结尾的字符input[-1:]。 - 未处理换行符:
readlines()读取的每行末尾会保留\n,可能干扰末尾数字的识别,需要先去除换行符。 - 内置函数名冲突:用
sum作为变量名会覆盖Python内置的sum()函数,建议改用total这类变量名。
修正后的代码
with open('textdocument.txt', 'r') as f: line_list = [line.strip() for line in f.readlines()] # 去除每行的换行符和首尾空白 total = 0 def num_concat(num1, num2): return int(f"{num1}{num2}") def find_first_number(s): while s: # 检查拼写形式的数字 if s.startswith("one"): return 1 elif s.startswith("two"): return 2 elif s.startswith("three"): return 3 elif s.startswith("four"): return 4 elif s.startswith("five"): return 5 elif s.startswith("six"): return 6 elif s.startswith("seven"): return 7 elif s.startswith("eight"): return 8 elif s.startswith("nine"): return 9 elif s.startswith("zero"): return 0 # 检查阿拉伯数字 elif s[0].isdigit(): return int(s[0]) # 都不是,去掉第一个字符继续查找 else: s = s[1:] def find_last_number(s): while s: # 检查拼写形式的数字 if s.endswith("one"): return 1 elif s.endswith("two"): return 2 elif s.endswith("three"): return 3 elif s.endswith("four"): return 4 elif s.endswith("five"): return 5 elif s.endswith("six"): return 6 elif s.endswith("seven"): return 7 elif s.endswith("eight"): return 8 elif s.endswith("nine"): return 9 elif s.endswith("zero"): return 0 # 检查阿拉伯数字 elif s[-1].isdigit(): return int(s[-1]) # 都不是,去掉最后一个字符继续查找 else: s = s[:-1] def calculate(line): first = find_first_number(line) last = find_last_number(line) return num_concat(first, last) for line in line_list: total += calculate(line) print(total)
额外优化说明
- 函数名改用Python规范的蛇形命名(如
find_first_number),可读性更强。 - 将数字判断拆分为拼写形式和阿拉伯数字两个独立分支,逻辑更清晰,避免原代码中复杂的或运算。
- 用
for循环遍历行列表,比while循环更简洁直观。
内容的提问来源于stack exchange,提问作者Tenmonster18
相关产品推荐
相关产品推荐

