← Questions
Valid number: decide whether a string is a decimal number
0
I was asked this
No reports yet. Sign in to say where you were asked it.
Return whether a string is a valid decimal number. Write down the exact rules first, then implement them cleanly.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
is_number(s: str) -> bool— after trimming leading and trailing spaces, the whole string must match:number := sign? (digits '.' digits? | '.' digits | digits) exponent?exponent := ('e' | 'E') sign? digits-
sign := '+' | '-';digits := one or more of 0-9
Example
valid: "0" "-3.14" "+.8" "2e10" "-1.2E-3" "4." "3e+7"
invalid: "abc" "1a" "e9" "." "+" "1e" "--6" "1e2.5"
Constraints
-
1 <= len(s) <= 20; letters, digits,+,-,., spaces.
Clarifying questions
- Are leading and trailing spaces allowed? Spaces inside?
- Is
"4."valid?".5"?"."? - Can the exponent be fractional or signed?
- Are hexadecimal,
"inf"or"NaN"in scope?
What a strong answer covers
- The grammar stated before any code, agreed with the interviewer.
- A single pass with flags (
seen_digit,seen_dot,seen_exp,digit_after_exp): a sign only at the start or right aftere; a dot only before anyeand only once;eonly once and only after a digit; at least one digit aftere. - Or an explicit finite-state machine with named states, which is easier to extend and test.
- Why a library call or a regular expression may not be acceptable, and how to test the parser against a table of cases.
- Tests: each rule's boundary, such as
".","e","+e1","1e+"," 1 ".
Follow-ups
- Return the parsed value as well, without using the language's float parser.
- Add thousands separators or hexadecimal literals.
- Report the position of the first invalid character.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
