easy +10 pts

Parse Error Recovery

Robustly parse a whitespace-separated string into a list of valid integers, skipping invalid tokens.

Implement a function `parse_numbers(text: str) -> list` that takes a string `text` and parses it into a list of integers. The input is a sequence of tokens separated by whitespace (spaces, tabs, newlines). Each token can be either a valid integer (optionally signed, e.g., `123`, `-45`, `+7`) or an invalid token (any other non-empty token). The parser must recover from errors: when encountering an invalid token, skip it and continue with the next token, so that valid numbers are still collected. Your function should not raise exceptions; it should return the list of successfully parsed integers in the order they appear. Use exception handling (try/except) to detect invalid tokens. Empty tokens (e.g., from consecutive spaces) should be ignored. Function signature: `def parse_numbers(text: str) -> list:` For example, `parse_numbers("1 abc 2 -3")` returns `[1, 2, -3]`. The input string may be empty, in which case return `[]`.

Constraints

- `text` is a string of length up to 100,000. - Tokens are separated by whitespace (spaces, tabs, newlines). - A valid integer is an optionally signed sequence of decimal digits, with no spaces inside. - Invalid tokens include things like `12.5`, `0x1F`, `1.0`, or non-numeric strings. - The resulting list may be empty. - Time complexity should be O(n) where n is the length of the string.

Example

>>> parse_numbers("1 abc 2 -3")
[1, 2, -3]
>>> parse_numbers("10 20 30")
[10, 20, 30]
>>> parse_numbers("")
[]
>>> parse_numbers("  12.5  three  -4  five  ")
[-4]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Split the input by whitespace using `text.split()` to get tokens.
For each token, try `int(token)` inside a try block.
Catch `ValueError` to skip invalid tokens.
Return the collected list of valid integers.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.