(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.
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.