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

Question

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

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Find the number of uppercase letters in a list Program code:

#Recursive function 'count' to count the number of uppercase 
#letters in a list of characters.
def count(chars):
    return countHelper(chars, len(chars) - 1)

#Recursive helper function 'countHelper' to count the 
#number of uppercase letters in a list of characters.
def countHelper(chars, high):
    # Base case: If the highest index is less than 0, 
    #have checked all characters.
    if high < 0:
        return 0

    # Recursive case: Check if the character at the current index is uppercase.
    # If it is, increment the count by 1 and recursively call countHelper
    # with the previous index.
    count = countHelper(chars, high - 1)
    if chars[high].isupper():
        count += 1

    return count


# Prompt the user for input
chars = input("Enter a list of characters (without spaces): ")

# Convert the input string to a list of characters
chars = list(chars)

# Count the number of uppercase letters in the list
uppercase_count = count(chars)

# Display the result
print(f"The number of uppercase letters in the list is: {uppercase_count}")

Executed Output:

Enter a list of characters (without spaces): HelloPythonWorld
The number of uppercase letters in the list is: 3

 

0 0

Discussions

Post the discussion to improve the above solution.