首页 > 解决方案 > 我在黑客等级引擎中遇到 EOF 错误,而我在本地机器上的代码工作正常

问题描述

我在其上运行 python3 时在 Hacker rank 引擎中遇到此错误。

Traceback (most recent call last):
  File "Solution.py", line 8, in <module>
    name=input()
EOFError: EOF when reading a line

我的代码是这个

phonebook = {}
total_entries = int(input("Total number of entries: "))
if 1 <= total_entries <= 10 ** 5:
    print("Enter names and number separated by space:")
    for entries in range(0, total_entries):
        items = input("Enter here:")
        items = items.split(" ")
        phonebook[items[0]] = int(items[1])
queries = []
while True:
    queries.append(input("Enter name to be searched:"))
    k = queries[-1]
    if not k:
        break
if 1 <= len(queries) <= 10 ** 5:
    for query in queries:
        if query == '':
            exit(0)
        elif query in phonebook.keys():
            print(f"{query}={phonebook.get(query)}")
        else:
            print("Not found")

如果您需要,问题的链接是这样的:问题链接

代码在我的本地机器上运行良好。我不知道为什么它会出现这样的错误。请建议我能做什么!

标签: pythonpython-3.xdictionary

解决方案


根据 HackerRank 的问题,在 n 行输入之后,会有一些“随机”的输入行。所以你不知道输入何时结束。因此,您会收到“EOF 错误”。一种方法是使用标准输入,如下所示:

from sys import stdin

phone={}
n=int(input())
for i in range(0,n):
    name=input()
    phone[name]=input()
for i in stdin:
    name=input()
    re=phone.get(name,"none")
    if re!="none":        
        print("%s=%s"%(name,re))
    else:
        print("Not found")

不过你的逻辑是错误的。由于输入是在一行中进行的,而您是在两行输入而不是一行


推荐阅读