easy +10 pts

File Line Reader Generator

Build a lazy generator that yields non-empty lines from a file-like object, one at a time.

Write a generator function `read_nonempty_lines(file_obj)` in Python. It takes one argument: `file_obj`, a file-like object (e.g., an open file, an `io.StringIO` instance). The generator must iterate over the lines of `file_obj` and yield only the lines that are **non-empty** after stripping leading and trailing whitespace. Lines that become an empty string after stripping are skipped. The generator should be lazy: it must read lines one by one from the file-like object, not load all lines into memory at once. **Function signature:** `def read_nonempty_lines(file_obj):` The generator yields strings. Each yielded string should have leading and trailing whitespace removed (`strip()`). **Important:** The function must be a generator function. That means it must contain `yield` (or `yield from`) inside its body. If no non-empty lines exist, the generator yields nothing. Your solution will be tested with file-like objects that support iteration and `.readline()` (as standard files do). Do not close the file object. **Testing note:** In the automated tests, a plain string may be passed as the file-like object. In that case, treat it as the entire content of a file and split on newline characters, so that each logical line is processed just like with a real file object.

Constraints

- `file_obj` is any iterable of strings that behaves like a file (supports iteration over lines), or a plain string containing newline characters - Each line may contain arbitrary characters, including newline characters - The file could have thousands of lines; memory must be O(1) (not O(n) lines) - Time complexity should be O(total characters processed)

Example

>>> import io
>>> file_obj = io.StringIO('hello world\n\n   \nfoo  bar\n')
>>> list(read_nonempty_lines(file_obj))
['hello world', 'foo  bar']

>>> file_obj = io.StringIO('\n\n   \n')
>>> list(read_nonempty_lines(file_obj))
[]

>>> file_obj = io.StringIO('single\n')
>>> list(read_nonempty_lines(file_obj))
['single']
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a for loop over `file_obj` to iterate over lines lazily.
Remember to call `.strip()` on each line and check if the result is truthy (non-empty) before yielding.
If the argument is a plain string, first split it into lines using `splitlines()` before processing.
The generator should not close the file; let caller manage it.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.