You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

未知输入行数的循环处理问题——以Doggopher Kattis题为例

问题澄清与代码修复指导

输入规则说明

Kattis该题的输入格式为:

  • 第一行:地鼠坐标 (gx, gy) 和狗的坐标 (dx, dy),四个浮点数。
  • 后续若干行:每行一个地鼠洞的坐标 (x, y),输入无固定行数,直到输入流结束(比如控制台输入时按Ctrl+D/Unix或Ctrl+Z/Windows,或文件读取到末尾)。

你的代码存在的问题

  1. 异常捕获不全面:当输入流结束时,sys.stdin.readline() 返回空字符串,此时执行 x, y = map(float, ...) 会抛出 ValueError(而非 EOFError),你的代码未捕获该异常,会导致程序崩溃。
  2. 未及时终止循环:找到符合条件的地鼠洞后,程序仍会继续读取后续输入,直到输入结束,虽然最终结果可能正确,但不符合题目“找到第一个可行洞就终止”的要求,且可能触发不必要的错误。

修复后的代码

import sys

def distance_squared(x1, y1, x2, y2):
    return (x1 - x2) ** 2 + (y1 - y2) ** 2

# 读取第一行的地鼠和狗坐标
gx, gy, dx, dy = map(float, sys.stdin.readline().split())
found_escape = False

while True:
    line = sys.stdin.readline()
    # 判断输入是否结束
    if not line:
        break
    x, y = map(float, line.strip().split())
    # 计算地鼠到洞的距离平方的4倍,与狗到洞的距离平方比较
    gopher_dist_sq = distance_squared(gx, gy, x, y)
    dog_dist_sq = distance_squared(dx, dy, x, y)
    if 4 * gopher_dist_sq < dog_dist_sq:
        print(f'The gopher can escape through the hole at ({x:.3f},{y:.3f}).')
        found_escape = True
        # 找到后立即终止循环,无需继续处理后续输入
        break

if not found_escape:
    print("The gopher cannot escape")

关键修复点解释

  • 输入结束判断:通过检查 readline() 返回的行是否为空,直接终止循环,避免异常抛出。
  • 及时终止逻辑:找到可行洞后,使用 break 跳出循环,立即停止处理后续输入,符合题目要求。
  • 代码可读性优化:重命名函数为更符合Python风格的 distance_squared,使用f-string格式化输出,提升代码清晰度。

内容的提问来源于stack exchange,提问作者Luleh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 16:45:03