나는 이렇게 학습한다/Algorithm & SQL

Initialize my name

daco2020 2022. 5. 7. 19:59
반응형

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.

 

 

 

반응형