非文件输入场景下EOF检测方法——解决HackerRank字典映射问题
Hey there! I get why that counter hack feels clunky—let's replace it with a clean, Pythonic way to detect when standard input ends without relying on arbitrary limits.
The Problem with Your Current Code
The input() function throws an EOFError when there's no more input to read (like when the test case finishes feeding queries). Your counter avoids infinite loops but doesn't handle the root cause of that error, making it a messy workaround.
Solution 1: Catch EOFError with Try-Except
This is the most straightforward approach. We wrap the input() call in a try block, and break the loop gracefully when EOFError is raised:
# Assume phone_book is already populated with your name-number pairs try: while True: query = input() if query in phone_book: print(f"{query}={phone_book[query]}") else: print("Not found") except EOFError: pass
As soon as there's no more input to read, the exception is caught, and we exit the loop automatically—no counters needed.
Solution 2: Iterate Over sys.stdin
Another clean method is to iterate directly over sys.stdin, which stops automatically when input ends. You'll just need to import the sys module first:
import sys # Assume phone_book is already populated for query in sys.stdin: query = query.strip() # Remove trailing newline characters to match dictionary keys if query in phone_book: print(f"{query}={phone_book[query]}") else: print("Not found")
The strip() call is important here—each line from sys.stdin includes a trailing newline, so we need to remove it to properly match the names stored in your dictionary.
Full Working Example
Putting it all together (including reading the initial phone book entries):
n = int(input()) phone_book = {} for _ in range(n): name, number = input().split() phone_book[name] = number # Using the try-except method for clean EOF handling try: while True: query = input() print(f"{query}={phone_book[query]}" if query in phone_book else "Not found") except EOFError: pass
Both solutions handle input termination correctly without triggering EOFError or relying on arbitrary counters. The try-except approach is great if you prefer explicit error handling, while the sys.stdin iteration is more concise and Pythonic.
内容的提问来源于stack exchange,提问作者AkThao

