S2Q2 · Make Word from Last Characters of Qualifying Words¶
⚡ Quick Reference
Type: Full I/O problem
Core idea: filter words by minimum length and starting character, collect their last characters, print concatenated.
l, c = input().split()
l = int(l)
n = int(input())
result = ""
for _ in range(n):
word = input()
if len(word) >= l and word[0] == c:
result += word[-1]
print(result)
Key rules:
- Word qualifies if len(word) >= l AND word[0] == c (case-sensitive)
- Collect word[-1] for each qualifying word in order
- Print the concatenation - empty string if no words qualify (prints an empty line)
Problem Statement¶
Problem (I/O type)
Read minimum length l and starting character c. Read n words. Print the concatenation of the last characters of all words with len >= l and starting with c.
Example:
3 a
5
apple
ant
banana
anchor
cat
etr
Tracing the example¶
l=3, c="a"
| Word | len >= 3? |
word[0] == 'a'? |
Qualifies? | Last char |
|---|---|---|---|---|
apple |
✅ (5) | ✅ | ✅ | e |
ant |
✅ (3) | ✅ | ✅ | t |
banana |
✅ (6) | ❌ (starts with 'b') | ❌ | - |
anchor |
✅ (6) | ✅ | ✅ | r |
cat |
✅ (3) | ❌ (starts with 'c') | ❌ | - |
Result: "e" + "t" + "r" = "etr" ✓
Solution approaches¶
l, c = input().split()
l = int(l)
n = int(input())
result = "".join(
input()
for _ in range(n)
if (word := input()) and len(word) >= l and word[0] == c
)
print(result)
Walrus operator reads input twice
The above has a bug - input() is called twice per iteration (once in the generator expression and once in the condition). Use the explicit loop below instead.
Key takeaways¶
Two conditions - length AND starting character
Both len(word) >= l and word[0] == c must be true. Short-circuit and skips the character check if the word is already too short.
Case-sensitive - c is used as-is
The problem specifies case-sensitive matching. word[0] == c distinguishes 'a' from 'A'. No .lower() should be applied.
print("") outputs an empty line
When no words qualify, result is an empty string. print("") outputs a blank line - exactly the required output for the no-results case.