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:16 | ISBN:978013274719 | Edition: 6

Question

(Occurrences of a specified character in a list) Write a recursive function that finds the number of occurrences of a specified character in a list. You need to define the following two functions. The second one is a recursive helper function.
def count(chars, ch):
def countHelper(chars, ch, high):
Write a test program that prompts the user to enter a list of characters in one line, and a character, and displays the number of occurrences of the character in the list.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Python code:

# Recursive function to count the occurrences of
#a specified character in a list.
def count(chars, ch):
    return countHelper(chars, ch, len(chars) - 1)

#Recursive helper function to count the 
#occurrences of a specified character in a list.
def countHelper(chars, ch, high):
    # Base case: If we have reached the beginning of the list, return 0.
    if high < 0:
        return 0

    # Recursive case: Count the occurrences of the character in the sublist
    # from index 0 to high-1, and add 1 if the character at 
    #the high index matches the specified character.
    count = countHelper(chars, ch, high - 1)
    if chars[high] == ch:
        count += 1

    return count


# Prompt the user for input
char_list = list(input("Enter a list of characters in one line: "))
char = input("Enter a character to count: ")

# Count the occurrences of the character in the list
occurrences = count(char_list, char)

# Display the result
print(f"The number of occurrences of '{char}' in the list is: {occurrences}")

Executed Output:

Enter a list of characters in one line: hello Python world
Enter a character to count: o
The number of occurrences of 'o' in the list is: 3

 

0 0

Discussions

Post the discussion to improve the above solution.