SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
5.recursion
Exercise:
Programming Excercises
Question:10 | ISBN:978013274719 | Edition: 6

Question

(Occurrences of a specified character in a string) Write a recursive function that finds the number of occurrences of a specified letter in a string using the following function header.
                                def count(s, a):
For example, count("Welcome", 'e') returns 2. Write a test program that prompts the user to enter a string and a character, and displays the number of occurrences for the character in the string.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Occurrences of a specified character in a string Program code:

#Recursive function to count the occurrences of a specified letter in a string.
def count(s, a):
    # Base case: If the length of the string is 0, there are no more characters to check.
    if len(s) == 0:
        return 0
    
    # Recursive case: Check if the first character of the string
    #is equal to the specified letter.
    # If it is, increment the count and recursively call count
    #with the remaining characters. If it's not, simply recursively
    #call count with the remaining characters.
    if s[0] == a:
        return 1 + count(s[1:], a)
    else:
        return count(s[1:], a)


# Prompt the user for input
s = input("Enter a string: ")
a = input("Enter a character to count: ")

# Count the occurrences of the character in the string
occurrences = count(s, a)

# Display the result
print(f"The character '{a}' occurs {occurrences} times in the string.")

Executed Output:

Enter a string: Welcome
Enter a character to count: e
The character 'e' occurs 2 times in the string.

 

0 0

Discussions

Post the discussion to improve the above solution.