本地运行正常的Python代码提交Py4e后出现NaN错误求助
问题:代码本地运行正常,Py4e平台提交后返回
Average spam confidence: nan 原代码
# objective: look for "the lines", count the lines, extract floating point and compute average try: fhand = open(input("File you'd like to open: ")) except: print("File not found.\n") quit() total = 0.0 count = 0.0 numbers = "" for lines in fhand: if lines.startswith("X-DSPAM-Confidence:"): count += 1 for words in lines: # turn string to float try: if words in "0123456789.": numbers = numbers + words elif words not in "0123456789.": total = total + float(numbers) numbers = "" except: continue print(f"Average spam confidence: {total/count}")
问题描述
本地VSCode中运行代码一切正常,但提交到Py4e平台后,输出显示Average spam confidence: nan,附带错误回溯截图。
问题原因
nan(非数字)是因为执行了0/0的无效运算,核心问题有两点:
- 逐个字符提取数字的逻辑存在漏洞:当行尾数字没有后续非数字字符触发累加时,拼接好的数字字符串无法加入
total;或者空字符串转float的错误被捕获后,后续逻辑异常导致total始终为0。 - 未处理
count=0的情况:如果平台测试文件中没有匹配X-DSPAM-Confidence:的行,或行首有空格导致startswith匹配失效,就会触发0/0运算。
修复方案
方案1:简化数字提取逻辑(推荐)
放弃逐个字符遍历,直接通过字符串分割提取数字,逻辑更简洁可靠:
# objective: look for "the lines", count the lines, extract floating point and compute average try: fhand = open(input("File you'd like to open: ")) except: print("File not found.\n") quit() total = 0.0 count = 0 for line in fhand: if line.startswith("X-DSPAM-Confidence:"): count += 1 # 分割字符串并提取数字部分 num_part = line.split(':')[1].strip() total += float(num_part) if count == 0: print("No valid spam confidence lines found.") else: print(f"Average spam confidence: {total/count}")
方案2:修复原逻辑漏洞
如果要保留原思路,需在每行遍历结束后处理剩余数字,并增加count=0的判断:
# objective: look for "the lines", count the lines, extract floating point and compute average try: fhand = open(input("File you'd like to open: ")) except: print("File not found.\n") quit() total = 0.0 count = 0.0 numbers = "" for lines in fhand: if lines.startswith("X-DSPAM-Confidence:"): count += 1 numbers = "" # 处理新行前清空缓存 for char in lines: # 变量名改为char更贴合语义 try: if char in "0123456789.": numbers += char else: if numbers: # 仅当缓存非空时才转换累加 total += float(numbers) numbers = "" except: continue # 行遍历结束后,检查是否有未处理的数字缓存 if numbers: total += float(numbers) if count == 0: print("No valid spam confidence lines found.") else: print(f"Average spam confidence: {total/count}")
内容的提问来源于stack exchange,提问作者Tam Marshall
相关产品推荐
相关产品推荐

