Katkat

Count Space-Separated Words Made Only of Letters and Basic Punctuation

VisaSoftware Engineer · Online Assessment

Last updated

A string-processing coding problem: split a sentence on spaces and count the tokens that contain only English letters and the punctuation marks comma, period, question mark and exclamation mark. It tests careful tokenization with repeated spaces and exact character-class rules.

Count the words in a sentence under a strict definition of a word. Split the sentence on spaces into tokens, discard every token that contains a digit or any character other than an English letter, a comma, a period, a question mark or an exclamation mark, and return the number of tokens that remain.

Function Signature

def count_valid_words(sentence: str) -> int:

Rules

  • Tokens are the maximal runs of non-space characters. Leading, trailing and repeated spaces never produce empty tokens.
  • A token is kept if every one of its characters is an English letter (a–z or A–Z) or one of the four punctuation marks , . ? !. Where the punctuation appears inside the token does not matter.
  • A token is discarded if it contains a digit, or any other character such as an apostrophe, a hyphen, a bracket, a colon or a quotation mark.
  • A token made only of the allowed punctuation marks, such as , or !!, is kept.
  • Return the number of kept tokens. An empty sentence, or one made only of spaces, gives 0.

Constraints

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

Examples

Example 1

Input: sentence = "He has 1 million do[[ars, isnt he?"
Output: 5

The tokens are He, has, 1, million, do[[ars,, isnt and he?. The token 1 contains a digit and do[[ars, contains [, so both are discarded and five tokens remain.

Example 2

Input: sentence = "Wait!! Is it 9am? Yes, it is."
Output: 6

Only 9am? is discarded, because it contains a digit.

Example 3

Input: sentence = " don't use e-mail , ok "
Output: 3

The tokens are don't, use, e-mail, , and ok. The apostrophe and the hyphen disqualify two tokens; the lone comma is kept because it contains only allowed punctuation.