Skip to content Skip to sidebar Skip to footer

Counting Words Starting With A Character

Write a function that accepts a string and a character as input and returns the count of all the words in the string which start with the given character. Assume that capitali

Solution 1:

You function misses the first t because in this line

if (input_str[i] ==characterand input_str[i -1] == " "):

when i is 0, then input_str[i - 1] is input_str[-1] which Python will resolve as the last character of the string!

To fix this, you could change your condition to

if input_str[i] == character and(i == 0 or input_str[i - 1] == " "):

Or use str.split with a list comprehension. Or a regular expression like r'(?i)\b%s', with (?i) meaning "ignore case", \b is word boundary and %s a placeholder for the character..

Solution 2:

Instead of looking for spaces, you could split input_str on whitespace, this would produce a list of words that you could then test against character. (Pseudocode below)

function F sentence, character {
    l = <sentence split by whitespace> 

    count = 0
    for word in l { 
       if firstchar(word) == character { 
          count = count + 1
       }   
    }

    return count
}

Solution 3:

Although it doesn't fix your specific bug, for educational purposes, please note you could rewrite your function like this using list comprehension:

def count_input_character (input_str, character):
    return len([x for x in input_str.lower().split() if x.startswith(character.lower())])

or even more efficiently(thanks to tobias_k)

def count_input_character (input_str, character):
    sum(w.startswith(character.lower()) for w in input_str.lower().split())

Solution 4:

def c_upper(text, char):
   text = text.title() #set leading charof words to uppercase
   char = char.upper() #set given charto uppercase
   k = 0 #counter
   for i intext:
     if i.istitle() and i == char: #checking conditions for problem, where i is a charin a given string
        k = k + 1return k

Post a Comment for "Counting Words Starting With A Character"