编写HackerRank消息解码程序时遭遇EOFError问题求助
EOFError 解决方法:HackerRank 解码程序问题
问题描述
编写HackerRank解码程序时遇到EOFError,程序功能为接收映射字典msg_dict、消息数量整数no_of_messages、待解码消息列表,返回无空格的解码消息列表。错误信息如下:
Traceback (most recent call last): File "/tmp/submission/20221104/11/52/hackerrank-cc4efe99dc145dc161f1a763dbcdf2e1/code/Solution.py", line 56, in <module> msg_dict_count = int(input().strip()) EOFError: EOF when reading a line
预期运行效果
示例输入0:
9 r 5 l 7 w 3 h 1 d 0 u 4 o 9 y 2 e 6 2 d h y u y r w u u r y h w e u h e h d d
示例输出0:
hello world
当前代码
#!/bin/python3 import math import os import random import re import sys # # Complete the 'decode_messages' function below. # # The function is expected to return a LIST_OF_STRINGS - the list of decoded messages. # The function accepts the following parameters: # 1. DICTIONARY msg_dict - the dictionary to be used to decode each character # 2. INTEGER no_of_messages - the number of messages in the list to be decoded # 3. LIST_OF_STRINGS messages - the list of messages with each character (in each message) separated by space # # Write your code here def decode_messages(msg_dict,no_of_messages,messages): decodeList=[] for i in range(no_of_messages): decodeList.append([]) for j in range(0,len(messages[i]),2): if messages[i][j+1]!='': decodeList[i].append(msg_dict[messages[i][j]]+msg_dict[messages[i][j+1]]) #add consecutive characters of messages return decodeList n=int(input()) msg_dict={} #storing pair consisting of letter and key messages=[] for i in range(n): a,b=input().split() msg_dict[a]=int(b) no_of_messages=int(input()) for i in range(no_of_messages): messages.append(input().split()) decoded_list=decode_messages(msg_dict,no_of_messages,messages) keys=list(msg_dict.keys()) values=list(msg_dict.values()) decodedMsgs="" for i in decoded_list: for j in i: decodedMsgs=decodedMsgs+keys[values.index(j)] #get key corresponding to print(decodedMsgs) decodedMsgs="" if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') msg_dict_count = int(input().strip()) msg_dict = {} for _ in range(msg_dict_count): key_val = input().rstrip().split() msg_dict[key_val[0]] = key_val[1] messages_count = int(input().strip()) messages = [] for _ in range(messages_count): messages_item = input() messages.append(messages_item) decoded_msgs = decode_messages(msg_dict, messages_count, messages) fptr.write('\n'.join(decoded_msgs)) fptr.write('\n') fptr.close()
错误原因与解决方法
核心问题
你的代码存在重复读取输入的问题:
- 在
if __name__ == '__main__':块之外,你已经写了一整套读取输入、调用函数、打印结果的代码; - HackerRank的评判系统会执行
if __name__ == '__main__':块中的代码,这部分会再次尝试读取输入,但此时输入已被前面的代码读完,导致后续input()调用遇到EOF(文件结束符),触发EOFError。
同时,decode_messages函数逻辑错误,无法生成预期的解码结果,需要一并修正。
分步解决
删除冗余的输入读取代码
删掉if __name__ == '__main__':块之外的所有测试代码(从def decode_messages之后到if __name__之前的部分),只保留函数定义和if __name__块的代码。修正
decode_messages函数逻辑
原函数逻辑完全错误,需重新实现:- 反转
msg_dict,构建数字字符串:字符的映射,方便通过拼接后的数字查找目标字符; - 对每条消息按空格分割成字符列表,每两个字符为一组,拼接对应数字字符串;
- 通过反转后的字典找到对应字符,拼接成完整字符串后加入结果列表。
- 反转
修正后的函数:
def decode_messages(msg_dict, no_of_messages, messages): # 反转字典,构建数字到字符的映射 reversed_dict = {v: k for k, v in msg_dict.items()} decoded = [] for msg in messages: chars = msg.split() result = [] # 每两个字符一组处理 for i in range(0, len(chars), 2): # 拼接两个数字字符串 num_str = msg_dict[chars[i]] + msg_dict[chars[i+1]] # 找到对应的字符并添加到结果 result.append(reversed_dict[num_str]) # 拼接成完整字符串加入列表 decoded.append(''.join(result)) return decoded
- 保持字典值类型一致
在if __name__块中,读取的字典值是字符串类型,无需转换为整数,确保反转字典时类型匹配。
最终完整代码
#!/bin/python3 import math import os import random import re import sys # # Complete the 'decode_messages' function below. # # The function is expected to return a LIST_OF_STRINGS - the list of decoded messages. # The function accepts the following parameters: # 1. DICTIONARY msg_dict - the dictionary to be used to decode each character # 2. INTEGER no_of_messages - the number of messages in the list to be decoded # 3. LIST_OF_STRINGS messages - the list of messages with each character (in each message) separated by space # def decode_messages(msg_dict, no_of_messages, messages): reversed_dict = {v: k for k, v in msg_dict.items()} decoded = [] for msg in messages: chars = msg.split() result = [] for i in range(0, len(chars), 2): num_str = msg_dict[chars[i]] + msg_dict[chars[i+1]] result.append(reversed_dict[num_str]) decoded.append(''.join(result)) return decoded if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') msg_dict_count = int(input().strip()) msg_dict = {} for _ in range(msg_dict_count): key_val = input().rstrip().split() msg_dict[key_val[0]] = key_val[1] messages_count = int(input().strip()) messages = [] for _ in range(messages_count): messages_item = input() messages.append(messages_item) decoded_msgs = decode_messages(msg_dict, messages_count, messages) fptr.write('\n'.join(decoded_msgs)) fptr.write('\n') fptr.close()
内容的提问来源于stack exchange,提问作者user20413640
相关产品推荐
相关产品推荐

