The EOFError python in online IDE's, the online solutions don't work for me

201 Views Asked by At

This is a program that creates a phone library with an input giving by the online IDE from Hackerank (python 3), then the code has to make a comparison between the names in the phone book and with a new input of names, and then it prints some statements. The IDE makes some tests. At the beginning it made an EOFError. Then I implemented a new solution, trying to avoid this error and it worked in 2 out of 6 tests. Then, the new error is "Time Limited Exceed"..One of the condition from this exercise is: "After the n lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains a to look up, and you must continue reading lines until there is no more input". I paste the code about:

import sys
try:
    n = int(input().strip())
    phone_list = {}
    for i in range(0, n):
        a = input().lower().split()
        phone_list[f"{a[0]}"] = int(a[1]) 
       
    friends = list(phone_list.keys())
          
    while input:
        name = str(input().strip())        
        if name in friends:
            print(f"{name}={phone_list[name]}")
        else:
            print("Not found")
except EOFError:
    sys.exit()  

this is the referent webpage and the task: hackerrank.com/challenges/30-dictionaries-and-maps/problem

3

There are 3 best solutions below

6
Grismar On

The problem is here:

while input:
   name = str(input().strip())

Since the value of bool(input) is always True (you're converting the action function input to a boolean value, which is truthy), this loop never ends.

You probably wanted something like this in Python >= 3.8:

while (name := input()):        
    name = name.strip()
    if name in friends:
        print(f"{name}={phone_list[name]}")
    else:
        print("Not found")

Or in older versions:

name = input()
while name:        
    name = name.strip()
    if name in friends:
        print(f"{name}={phone_list[name]}")
    else:
        print("Not found")
    name = input()

However, note that this is problematic as well:

for i in range(0, n):
        a = input().lower().split()
        phone_list[f"{a[0]}"] = int(a[1]) 

What if there aren't n entries? Your script would be waiting for more data to arrive indefinitely. However, I assume that in the specific setup you're in, that would generate an EOFError, but note that this is not generally a good pattern.

0
nigh_anxiety On

You should limit the try/except block to just the lines getting input. It's really only needed when checking the "unknown" part of the file, but I added a check at the start in case the file is totally blank.

import sys
try:
    n = int(input().strip())
except EOFError:
    #Invalid input file
    sys.exit(1)

phone_list = {}
for i in range(0, n):  # The 0 is redundant
    a = input().lower().split()  # You could use unpacking here instead of a single list
    phone_list[f"{a[0]}"] = int(a[1]) #Converting the number to an int isn't needed

# Instead of getting a list of all the keys, you could consider using dict.get()
# or try/except to catch the KeyError.       
friends = list(phone_list.keys())
while True:          
    try:
        name = str(input().strip())        
    except EOFError:
        break
    else:
        if name in friends:
            print(f"{name}={phone_list[name]}")
        else:
            print("Not found")

I added comments for some other suggestions above.

0
Alcadenas2228stack On

The problem was the way the dic was made in the first version when appeared to many entries, the code took so long that the online IDE failed to past the test.

n = int(input())
number_list = []
for i in range(n):
    number_list.append(input().split())
phone_list = {g: v for g, v in number_list} # a better and fast way to do the dic

while True:
    try:
        name = input()
        if name in phone_list:
            print(f"{name}={phone_list[name]}")
        else:
            print("Not found")
    except:
        break