Count Words Ending with 'y' in a String
Problem:
Given an English sentence containing spaces and multiple words (up to 100 characters), count the number of words ending with the letter 'y'.
Input:
Input a single sentence.
Output:
Output the number of words.
Example:
Input: 'today is my 16th birthday'
Output: 3
Solution:
- Split the sentence into words using spaces as separators.
- Iterate through each word and check if the last letter is 'y'.
- Increment a counter for each word ending with 'y'.
- Output the final counter value.
Reference Code:
def count_y_words(sentence):
words = sentence.split()
count = 0
for word in words:
if word[-1] == 'y':
count += 1
return count
# Example usage
sentence = 'today is my 16th birthday'
result = count_y_words(sentence)
print(result) # Output: 3
原文地址: http://www.cveoy.top/t/topic/nQST 著作权归作者所有。请勿转载和采集!