KatInterview

Validate a Plain Signed Decimal Literal

StringsAuto-graded · 25 test cases
MediumAuto-gradedStringsstringsparsingvalidation

Last updated

Check whether a string is a well-formed plain decimal literal (optional sign, digits, optional fraction) by turning a small grammar into a careful single-pass validator.

Write a function that reports whether a given string is a well-formed decimal literal in plain notation. Only a sign, digits, and a single fractional part are allowed. Exponents and any other symbols are not.

Task

Given a string text, return True if the entire string follows the pattern below, and False otherwise.

Format

A valid string consists of these parts, in this order, with nothing before or after:

  1. An optional sign: a single + or -.
  2. The integer part: one or more decimal digits.
  3. An optional fractional part: one . followed by one or more decimal digits.

Implications

  • "234", "-455", and "23.23" are valid.
  • "1e2" is invalid (no exponent notation), and "12^2" is invalid (^ is not permitted).
  • "2.2.4" is invalid because it contains more than one decimal point.
  • Leading zeros are fine: "007" and "-0" are valid.
  • These are all invalid: "", "-", ".5", "5.", and any string that contains whitespace.

Allowing a leading +, allowing leading zeros, and demanding digits on both sides of the decimal point are rules of this exercise.

Constraints

  • 0 <= len(text) <= 100
  • text consists of printable characters, spaces included.
  • A "digit" is any character for which Python's str.isdigit() returns True (for ordinary ASCII input this is exactly 0 through 9).
  • Return a Python bool.

Examples

Example 1

Input: is_plain_decimal('-455')

Output: True

Example 2

Input: is_plain_decimal('23.23')

Output: True

Example 3

Input: is_plain_decimal('2.2.4')

Output: False

Example 4

Input: is_plain_decimal('234')

Output: True

Hints

Hint 1

Write the format as a tiny grammar first: optional sign, then at least one digit, then optionally a dot followed by at least one digit.

Hint 2

Scan with a single index. Consume the sign if present, then a run of digits, then the optional dot and its run of digits. Each run must be non-empty where the format requires it.

Hint 3

After the scan, the whole string must be consumed. Leftover characters (a second dot, a letter, a space) mean the answer is False.