S2Q1 · Last Word Starting with Uppercase Letter¶
⚡ Quick Reference
Function: last_word_starts_with_upper_case(sentence: str)
Core idea: split into words, scan left-to-right, keep overwriting result every time a match is found. The final value is the last match.
def last_word_starts_with_upper_case(sentence: str):
result = None
for word in sentence.split():
if word[0].isupper():
result = word
return result
Key rules:
- Returns None if no uppercase-starting word exists
- word[0].isupper() checks only the first character
- Loop always finishes - "last wins" overwrite pattern
Problem Statement¶
Problem
Write a function last_word_starts_with_upper_case(sentence) that returns the last word whose first character is uppercase, or None if no such word exists.
Examples:
"This is a Test sentence"
"Test"
"no uppercase words here"
None
Tracing the example¶
Sentence: "This is a Test sentence"
| Word | word[0].isupper()? |
result after |
|---|---|---|
"This" |
✅ | "This" |
"is" |
❌ | "This" |
"a" |
❌ | "This" |
"Test" |
✅ | "Test" |
"sentence" |
❌ | "Test" |
Return → "Test"
Solution approaches¶
Key takeaways¶
"Last wins" overwrite
Init to None, overwrite on every match, return after the loop finishes. The final value is always the last match - no index tracking needed.
word[0].isupper() checks first char only
str.isupper() on a single character tests if that character is uppercase. Calling it on the full word would require all characters to be uppercase - not what we want here.
next(reversed(...), None) for last match
Reversing and taking the first match is equivalent to finding the last match in the original order. next(..., None) safely returns None if no match exists.