반응형
Some people just have a first name; some people have first and last names and some people have first, middle and last names.
You task is to initialize the middle names (if there is any).
Examples
'Jack Ryan' => 'Jack Ryan'
'Lois Mary Lane' => 'Lois M. Lane'
'Dimitri' => 'Dimitri'
'Alice Betty Catherine Davis' => 'Alice B. C. Davis'
Solution:
1. If there are 3 or more elements of name, only the first letter of the middle elements is left.
2. In the first letter . appended and returned with the first and last elements.
3. If there are 2 or less elements of name, it is returned as is.
def initialize_names(name):
name_arr = name.split(' ')
if len(name_arr) > 2:
name_arr[1:-1] = [i[0] + "." for i in name_arr[1:-1]]
return ' '.join(name_arr)
Note that the sliced range can be reallocated as is.
반응형
'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글
Find the capitals (0) | 2022.05.09 |
---|---|
Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages (0) | 2022.05.08 |
Even numbers in an array (0) | 2022.05.06 |
Number of People in the Bus (0) | 2022.05.05 |
Disemvowel Trolls (0) | 2022.05.05 |