Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Count uppercase letters python 3.4 problem. Count_upper(word): Write a recursive

ID: 3818499 • Letter: C

Question

Count uppercase letters python 3.4 problem. Count_upper(word):

Write a recursive function count-upper () that takes a non-empty string as its argument and returns a count of how many letters in the string are uppercase letters. Your function must be recursive and must not use any loops. To solve this problem you will want to use the isupper () and islower () methods of string objects. For example, suppose we had the following variables: letter1 = 'g' letter2 = 'Q' letter1.isupper () would evaluate to False, whereas letter2.isupper () would evaluate to True.

Explanation / Answer

count uppercase letters:

def count_upper(s): # defing of count upper function
count = 0 # initilizing a count variable to 0

if not s: # checks for if string exist or not if not return 0
return 0

if str.isupper(s[0]): #checks for first letter of string is upper or not if upper then

return 1 + count_upper(s[1:]) '''increments count by 1 and call count_upper function with next letter in string until end of string'''

return count_upper(s[1:]) # finally returns count of upper case letters in the string

def main():
print(count_upper("Stony Brook University")) # Prints 3
print(count_upper('HAPPINESS')) # prints 9
print(count_upper('no more labs, yay!')) # prints 0

if __name__=='__main__':
main()

Sample Output:

3
9
0