KatInterview

Tally Clean Tokens in a Space-Delimited Line

StringsAuto-graded · 25 test cases
EasyAuto-gradedStringsstringsparsingtokenization

Last updated

Split a line on spaces and count the tokens made only of ASCII letters and the marks , . ? !, testing exact tokenization and character-class checks.

Tally Clean Tokens in a Space-Delimited Line

You are given a line of text. Break it into tokens at the spaces, then decide which tokens are "clean" according to a strict character rule. Return how many clean tokens the line contains.

Definitions

  • A token is a maximal run of consecutive non-space characters. Spaces at the start, at the end, or several in a row never create empty tokens.
  • A token is clean if every one of its characters is one of the following:
    • an English letter, a-z or A-Z
    • a comma ,
    • a period .
    • a question mark ?
    • an exclamation mark !
  • Where the punctuation sits inside a token is irrelevant. he?, ?he, h?e and !! are all clean.
  • A token is not clean if it contains a digit or any other character, for example an apostrophe, hyphen, bracket, colon, quotation mark, underscore or @.
  • A token consisting only of allowed punctuation, such as , or !!, is clean.

Task

Implement tally_clean_tokens(line) that returns the number of clean tokens in line. If line is empty or contains only spaces, return 0.

Constraints

  • 0 <= len(line) <= 10^5
  • Every character of line is printable ASCII (codes 32 to 126), so the space is the only whitespace character.

Examples

Example 1

Input: tally_clean_tokens('He has 1 million do[[ars, isnt he?')

Output: 5

Example 2

Input: tally_clean_tokens('Wait!! Is it 9am? Yes, it is.')

Output: 6

Example 3

Input: tally_clean_tokens(' don\'t use e-mail , ok ')

Output: 3

Hints

Hint 1

First turn the line into tokens. Think about what happens with leading, trailing and repeated spaces, and make sure empty pieces are never counted.

Hint 2

Rather than listing forbidden characters, define the set of allowed characters (52 letters plus , . ? !) and check each character of a token against it.

Hint 3

Do not add rules about punctuation position or count. A token is clean exactly when all of its characters are in the allowed set, including tokens made only of punctuation.