Number of Valid Words in a Sentence
Time waster. Avoid.
Here is the Python code which implements a solution for this problem:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
| class Solution:
def countValidWords(self, sentence: str) -> int:
# Define the punctuation characters.
punctuations = set(['!', '.', ','])
# Tokenize the sentence into words.
words = sentence.split()
# Initialize the count of valid words to 0.
valid_word_count = 0
# Iterate over each word.
for word in words:
# Count the hyphens, punctuation marks and digits in the word.
hyphen_count = word.count('-')
punctuation_count = sum([1 for char in word if char in punctuations])
digit_count = sum([1 for char in word if char.isdigit()])
# Check the conditions for a valid word.
if hyphen_count <= 1 and punctuation_count <= 1 and digit_count == 0:
# If a hyphen is present, it must be surrounded by lowercase characters.
if hyphen_count == 1:
hyphen_index = word.index('-')
if hyphen_index == 0 or hyphen_index == len(word) - 1 or not word[hyphen_index-1].isalpha() or not word[hyphen_index+1].isalpha():
continue
# If a punctuation mark is present, it must be at the end of the word.
if punctuation_count == 1:
if word[-1] not in punctuations:
continue
# If the word passed all checks, it is valid.
valid_word_count += 1
# Return the count of valid words.
return valid_word_count
|
This Python code follows the conditions mentioned in the problem statement to determine if a word is valid or not. It counts the number of hyphens, punctuation marks, and digits in each word, and checks if these counts satisfy the conditions for a valid word. If a word is valid, it increments the count of valid words. The function then returns the count of valid words.