S2Q2 · Abbreviate Initials and Sort (Last, F.M. Format)¶
⚡ Quick Reference
Type: Full I/O problem
Core idea: split each name, last part = surname, all other parts = initials joined without spaces; format as "Last, F.M.", sort, print.
n = int(input())
results = []
for _ in range(n):
parts = input().split()
last = parts[-1]
initials = "".join(p[0] + "." for p in parts[:-1])
results.append(f"{last}, {initials}")
for name in sorted(results):
print(name)
Key rules:
- Last name → parts[-1]
- All other parts → first letter + ".", concatenated with no spaces
- Format: "LastName, F.M."
- Sort alphabetically and print
Problem Statement¶
Problem (I/O type)
Read n full names. Convert each to "Last, Initials." format and print sorted alphabetically.
Example:
3
John Doe
Alice Johnson
Bob Alan Rickman
Doe, J.
Johnson, A.
Rickman, B.A.
Understanding the format¶
"John Doe" → parts = ["John", "Doe"]
last = "Doe", initials = "J."
→ "Doe, J."
"Alice Johnson" → parts = ["Alice", "Johnson"]
last = "Johnson", initials = "A."
→ "Johnson, A."
"Bob Alan Rickman" → parts = ["Bob", "Alan", "Rickman"]
last = "Rickman", initials = "B." + "A." = "B.A."
→ "Rickman, B.A."
Key difference from Set 1 S2Q2: the output format here is "Last, Initials." not "Initials. Last", and multiple initials are joined without a space between them.
Tracing the example¶
| Full name | last |
parts[:-1] |
initials |
Result |
|---|---|---|---|---|
"John Doe" |
"Doe" |
["John"] |
"J." |
"Doe, J." |
"Alice Johnson" |
"Johnson" |
["Alice"] |
"A." |
"Johnson, A." |
"Bob Alan Rickman" |
"Rickman" |
["Bob","Alan"] |
"B.A." |
"Rickman, B.A." |
Sorted: Doe, Johnson, Rickman ✓
Solution approaches¶
n = int(input())
results = []
for _ in range(n):
parts = input().split()
last = parts[-1]
# Build initials - no spaces between them
initials = ""
for part in parts[:-1]:
initials += part[0] + "."
formatted = last + ", " + initials
results.append(formatted)
results.sort()
for name in results:
print(name)
Key takeaways¶
"".join() - no spaces between initials
"".join(p[0] + "." for p in parts[:-1]) concatenates all initials without separators. "B." + "A." = "B.A." not "B. A." - the dot is part of each initial, not a separator.
Format is "Last, Initials." not "Initials Last"
This question uses surname-first format with a comma separator - different from the Set 1 version which used initials-first. Read the output format carefully each time.
Sort the formatted strings, not the originals
Format all names first, then sort. Sorting happens on the "Last, Initials." strings - alphabetical order by surname, which is what we want.