반응형
Description:
John has invited some friends. His list is:
s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill";
Could you make a program that
- makes this string uppercase
- gives it sorted in alphabetical order by last name.
When the last names are the same, sort them by first name. Last name and first name of a guest come in the result between parentheses separated by a comma.
So the result of function meeting(s) will be:
"(CORWILL, ALFRED)(CORWILL, FRED)(CORWILL, RAPHAEL)(CORWILL, WILFRED)(TORNBULL, BARNEY)(TORNBULL, BETTY)(TORNBULL, BJON)"
It can happen that in two distinct families with the same family name two people have the same first name too.
Notes
- You can see another examples in the "Sample tests".
Solution:
1. Create a two-dimensional array of names in a string.
2. Sort the two-dimensional array.
3. Converts to a string and returns it.
def meeting(s):
split_arr = [i.upper().split(':') for i in s.split(';')]
sorted_arr = sorted(split_arr, key=lambda x:(x[1], x[0]))
return ''.join([f"({i[1]}, {i[0]})" for i in sorted_arr])
Best Practices:
def meeting(s):
names = s.upper().split(';')
return ''.join(sorted('({1}, {0})'.format(*(n.split(':'))) for n in names))
def meeting(s):
return ''.join(f'({a}, {b})' for a, b in sorted(name.split(':')[::-1] for name in s.upper().split(';')))
반응형
'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글
자료구조 _ Linked List란? (0) | 2022.03.17 |
---|---|
자료구조 _ Array와 Dynamic Array (0) | 2022.03.17 |
English beggars (0) | 2022.03.16 |
Kebabize (0) | 2022.03.16 |
+1 Array (0) | 2022.03.15 |