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

两个单词非相邻组合Python代码IDLE运行正常在线IDE抛EOFError

错误成因与解决方案

成因

  1. 直接触发EOFError的核心原因是代码使用了while True死循环不断调用input()读取输入:本地IDLE是交互式运行环境,支持用户持续输入内容,不会触发输入流结束的情况;但绝大多数在线IDE的输入是预定义的固定内容,当所有预输入内容被读取完毕后,再调用input()就会因为没有内容可读抛出EOF(End of File,文件/流末尾)错误。
  2. 你粘贴的代码还存在缩进层级错误,non_adjacent函数内部的result = []及后续代码缩进多了一层,本地如果能正常运行大概率是你粘贴时格式错乱导致的,在线运行也需要先修正缩进问题。

解决方案

适配在线IDE单次输入场景

如果只需要处理一次输入,直接删除死循环即可,修正后完整代码如下:

def non_adjacent(words:str):
    words_list = words.split()
    result = []
    l = len(words_list)
    for i in range(l-2):
        for j in range(i+2, l):
            tmp1 = words_list[i]
            tmp2 = words_list[j]
            index_tmp1 = [k for k in range(l) if words_list[k]==tmp1]
            index_tmp2 = [m for m in range(l) if words_list[m]==tmp2]
            not_adj = True
            for el1 in index_tmp1:
                for el2 in index_tmp2:
                    if abs(el1 - el2) == 1:
                        not_adj = False
            tmp = sorted([tmp1, tmp2])
            if tmp not in result and not_adj:
                result.append(tmp)
    for el in sorted(result):
        print(*el)

if __name__ == "__main__":
    non_adjacent(input())

兼容多次输入场景

如果需要保留多次输入的能力,给循环加EOF异常捕获即可,读到输入末尾时正常退出不会报错,对应修改的代码片段如下:

if __name__ == "__main__":
    while True:
        try:
            input_content = input()
            non_adjacent(input_content)
        except EOFError:
            break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 15:36:02