Write the number branch of a hand-written lexer.
What to build
A program that scans a line character by character and prints every number in it.
Requirements
- A number is one or more digits, optionally followed by a dot and one or more digits. A dot not followed by a digit is not part of a number.
- Print each number on its own line, or
none. Do not use the re module.
Input
One line of text.
Output
The numbers, or none.
Constraints
At most 100 characters.
Example
Input:
x=12+3.5*y2
Output:
12
3.5
2
Why it works
One character of lookahead after the digits decides whether a dot starts a fraction, exactly as in a real scanner.
Examples
Example 1 · Input
x=12+3.5*y2
Expected output
12 3.5 2
Example 2 · Input
no digits here
Expected output
none
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Walk with an index; when you see a digit, keep moving while digits continue.
Hint 2
Take a dot only if a digit comes right after it.
Solution
Show one correct solution (try it yourself first)
text = input()
i = 0
found = []
while i < len(text):
if text[i].isdigit():
start = i
while i < len(text) and text[i].isdigit():
i += 1
if i + 1 < len(text) and text[i] == "." and text[i + 1].isdigit():
i += 1
while i < len(text) and text[i].isdigit():
i += 1
found.append(text[start:i])
else:
i += 1
print("\n".join(found) if found else "none")