gpt4 book ai didi

python - python Hackerrank 中的 EOF 错误

转载 作者:行者123 更新时间:2023-12-02 04:20:22 25 4
gpt4 key购买 nike

尝试解决问题,但 Hackerrank 的编译器在解析时不断抛出错误 EOFError:不知道哪里错了。

#!usr/bin/python

b=[]
b=raw_input().split()
c=[]
d=[]
a=raw_input()
c=a.split()
f=b[1]
l=int(b[1])
if(len(c)==int(b[0])):
for i in range(l,len(c)):
d.append(c[i])
#print c[i]
for i in range(int(f)):
d.append(c[i])
#print c[i]
for j in range(len(d)):
print d[j],

我也尝试过 try catch 来解决它,但没有得到任何输入。

try:
a=input()
c=a.split()
except(EOFError):
a=""

输入格式是开头为 2 个空格的整数,然后是数组

回溯错误是:

Traceback (most recent call last):
File "solution.py", line 4, in <module>
b=raw_input().split()
EOFError: EOF when reading a line

最佳答案

有多种方法可以处理 EOF 错误。

1.抛出异常:

while True:
try:
value = raw_input()
do_stuff(value) # next line was found
except (EOFError):
break #end of file reached

2.检查输入内容:

while True:
value = raw_input()
if (value != ""):
do_stuff(value) # next line was found
else:
break

3.使用 sys.stdin.readlines() 将它们转换为列表,然后使用 for-each 循环。更详细的解释是Why does standard input() cause an EOF error

import sys 

# Read input and assemble Phone Book
n = int(input())
phoneBook = {}
for i in range(n):
contact = input().split(' ')
phoneBook[contact[0]] = contact[1]

# Process Queries
lines = sys.stdin.readlines() # convert lines to list
for i in lines:
name = i.strip()
if name in phoneBook:
print(name + '=' + str( phoneBook[name] ))
else:
print('Not found')

关于python - python Hackerrank 中的 EOF 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43077261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com