Computers and Technology

Question

Write a function named word_beginnings that has two parameters line a string ch a character Return a count of words in line that start with ch. For the purposes of this exercise a word is preceeded by a space. Hint: add a space to the beginning of line For example if line is 'row row row your raft' and ch is 'r' the value 4 will be returned. Note: You can use lists in this question but try to solve it without lists.

1 Answer

  • Answer:

    The function in Python is as follows:

    def word_beginnings(line, ch):

       count = 0

       lines =line.split(" ")

       for word in lines:

           if word[0] == ch:

               count+=1

       return count

    Explanation:

    This defines the function

    def word_beginnings(line, ch):

    This initializes count to 0

       count = 0

    This splits line into several words

       lines =line.split(" ")

    This iterates through each word

       for word in lines:

    This checks if the first letter of each word is ch

           if word[0] == ch:

    If yes, increment count by 1

               count+=1

    Return count

       return count

NEWS TODAY

You May Be Interested