Write a method called letterCount that takes two String arguments, one containing some text and the other containing a single letter. This method should then compute and return the count of all of the occurrences of that letter in the given text.

Respuesta :

Answer:

I am writing a Python program.  Here is the function letterCount. This function takes two string arguments text and letter and return count of all occurrences of a letter in the text.

def letterCount(text, letter):  

 count = 0  # to count occurrences of letter in the text string

 for char in text:  # loop moves through each character in the text

   if letter == char: # if given letter matches with the value in char

     count += 1  # keeps counting occurrence of a letter in text

 return count # returns how many times a letter occurred in text

   

Explanation:

In order to see if this function works you can check by calling this function and passing a text and a letter as following:

print(letterCount('apples are tasty','a'))

Output:

3

Now lets see how this function works using the above text and letter values.

text = apples are tasty

letter = a

So the function has to compute the occurrences of 'a' in the given text 'apples are tasty'.

The loop has a variable char that moves through each character given in the text (from a of apples to y of tasty) so it is used as an index variable.

char checks each character of the text string for the occurrence of letter a.

The if condition checks if the char is positioned at a character which matches the given letter i.e. a. If it is true e.g if char is at character a of apple so the if condition evaluates to true.

When the if condition evaluates to true this means one occurrence is found and this count variable counts this occurrence. So count increments every time the occurrence of letter a is found in apples are tasty text.

The loop breaks when every character in text is traversed and finally the count variable returns all of the occurrences of that letter (a) in the given text (apples are tasty). As a occurs 3 times in text so 3 is returned in output.

The screen shot of program along with output is attached.

Ver imagen mahamnasir
ACCESS MORE
EDU ACCESS
Universidad de Mexico