Check Whether a String Is a Signed Decimal Number Without Exponent Notation
LinkedInSoftware Engineer · Technical ScreenLast updated
Write a function that decides whether a string is a valid plain decimal number with an optional sign and fractional part, rejecting exponents, stray symbols, and repeated decimal points. It tests turning a small grammar into careful character-by-character validation and covering edge cases such as empty strings and bare signs.
Implement a function that decides whether a string is a valid number in plain decimal notation: an optional sign, digits, and an optional fractional part. Exponent notation and any other symbols are not allowed.
Function Signature
is_number(to_test: str) -> bool
Rules
A string is valid exactly when the whole string matches this form, with nothing before or after it:
- An optional single sign character,
+or-. - One or more decimal digits
0through9. - Optionally, a single
.followed by one or more decimal digits.
Consequences of the rules:
"234","-455", and"23.23"are valid."1e2"is invalid because exponent notation is not supported, and"12^2"is invalid because^is not allowed."2.2.4"is invalid because at most one decimal point may appear.- Leading zeros are allowed, so
"007"and"-0"are valid. "","-",".5","5.", and any string containing whitespace are invalid.
Accepting +, allowing leading zeros, and requiring digits on both sides of a decimal point are conventions of this exercise.
Constraints
0 <= len(to_test) <= 100.to_testcontains only printable ASCII characters, including spaces.
Examples
Input: to_test = "-455"
Output: True
Input: to_test = "23.23"
Output: True
Input: to_test = "2.2.4"
Output: False
The second decimal point makes the string invalid.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.