To solve this problem, we need to create a function that counts the number of uppercase letters in a given string.
Approach
The approach involves iterating over each character in the input string and checking if it is an uppercase letter. We can efficiently count these uppercase characters using a generator expression combined with the sum() function. Here's the breakdown:
- Check for Uppercase: For each character in the string, use the
isupper()method to determine if it is uppercase. - Count: Sum up the number of characters that are uppercase (each uppercase character contributes 1 to the sum).
This approach is concise, Pythonic, and efficient as it processes each character exactly once with a time complexity of O(n), where n is the length of the string.
Solution Code
def count_uppercase(s):
return sum(1 for char in s if char.isupper())
Explanation
- Generator Expression: The generator expression
(1 for char in s if char.isupper())generates a sequence of 1s for each uppercase character in the strings. - Sum Function: The
sum()function adds up all the 1s from the generator expression, giving the total count of uppercase letters.
This solution handles all edge cases, including empty strings (returns 0), strings with no uppercase letters (returns 0), and strings with all uppercase letters (returns the length of the string). It is both efficient and easy to understand.
作者声明:本文包含人工智能生成内容。