프로그래밍 문제/[Python] CheckIO

[CheckIO] Backward Each Word

UltraLowTemp-Physics 2021. 3. 10. 01:00

Problem: py.checkio.org/en/mission/backward-each-word/
My solution: 

def backward_string_by_word(text: str) -> str:
    # your code here
    words_list = text.split()               # 
    list1 = list(text)                      # character list that would be substituted by reversed words
    list2 = list(text)                      # dummy list that is used to find an index of a word in the list 
    
    for word in words_list:
        dummy_str = "".join(list2)    # 
        index    = dummy_str.find(word)     # find the index of a word in the text  
        reversed = word[::-1]               # reverse the word 
        length   = len(reversed)       # the length of the word  
        list1[index:index+length] = list(reversed) 
        list2[index:index+length] = ['x' for n in range(length)]
        
    return "".join(list1)


if __name__ == '__main__':
    print("Example:")
    #print(backward_string_by_word(''))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert backward_string_by_word('') == ''
    assert backward_string_by_word('world') == 'dlrow'
    assert backward_string_by_word('hello world') == 'olleh dlrow'
    assert backward_string_by_word('hello   world') == 'olleh   dlrow'
    assert backward_string_by_word('welcome to a game') == 'emoclew ot a emag'
    print("Coding complete? Click 'Check' to earn cool rewards!")