Search code examples
pythonpython-3.xstdineof

How to detect EOF when input is not from a file?


I'm working through the HackerRank 30 days of code and I'm on day 8. The challenge is to take n lines of standard input of the form name phone-number and add these to a dictionary in key : value pairs of the format name : phone-number. That part was fine.

The next part of the input is an arbitrary number of lines, each containing a name. The task is to print the phone-number of each name or print "Not found" if the name is not in the dictionary.

My trouble lies in determining the end of the input.

The second part of my code is as follows:

counter = 0 # To prevent infinite loop
while 1:
    query = input()
    if query in phone_book:
        print("{}={}".format(query, phone_book[query]))
    elif query not in phone_book:
        print("Not found")
    else:
        break
    counter += 1
    if counter == 10000000:
        break

The if and elif statements check whether or not the name is in the dictionary and the else statement is meant to break out of the loop if there is no more input. However, I get an EOFError: EOF when reading a line error. My code passes all the tests, but I know there should be a better way to deal with the EOF than just setting an upper limit of 10000000 lines (if the input was more than 10000000 lines, I could just increase the counter limit, but I know that is not a good way of doing this).

I've looked at this page: How to find out whether a file is at its `eof`?

But I don't know how to implement this in my code, since the HackerRank input doesn't seem to be in a file from which I can read lines.

How could I manage the EOF issue and eliminate the need for a counter?

NB. The link to the HackerRank page: https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem


Solution

  • Just iterate over sys.stdin; then there is no need to explicitly check for the end of the input; the iterator will raise StopIteration when it reaches the ed of the input.

    import sys
    
    for query in sys.stdin:
        query = query.strip()
        if query in phone_book:
            print("{}={}".format(query, phone_book[query]))
        else:
            print("Not found")