ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 2023.7.23.일요일 D-8, "Forward, 8 days left" 96 to ?
    TIL( Today I Learned) 2023. 7. 23. 13:10
    • 글자 지우기
    문제 설명

    문자열 my_string과 정수 배열 indices가 주어질 때, my_string에서 indices의 원소에 해당하는 인덱스의 글자를 지우고 이어 붙인 문자열을 return 하는 solution 함수를 작성해 주세요.

    내것

    def solution(my_string, indices):
        msls = list(my_string)
        for i in indices:
            msls[i] = ''
        ms1 = ''.join(msls)
        return ms1

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    쳇 것

    def solution(my_string, indices):
        char_list = list(my_string)

        # Remove characters at the specified indices
        for i in indices:
            if 0 <= i < len(char_list):  # Check if the index is valid
                char_list[i] = ''

        # Join the remaining characters to form the new string
        new_string = ''.join(char_list)

        return new_string

    # Test the function
    my_string = "apporo"
    indices = [1, 2, 0, 3]
    result = solution(my_string, indices)
    print(result)  # Output: "pr"

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    남 것 

     

     

    def solution(my_string, indices):
        answer = ''
        for i in range(len(my_string)):
            if i not in indices:answer+=my_string[i]
        return answer
    

     

     

    def erase_letters(my_string, indices):
        char_list = list(my_string)

        # Sort the indices in descending order to avoid index shifting during removal
        sorted_indices = sorted(indices, reverse=True)

        # Remove characters at the specified indices
        for i in sorted_indices:
            if 0 <= i < len(char_list):  # Check if the index is valid
                char_list.pop(i)

        # Join the remaining characters to form the new string
        new_string = ''.join(char_list)

        return new_string

    이 함수는 my_string을 원래 문자열로 사용하고 indices를 삭제할 문자의 색인을 나타내는 정수 배열로 사용합니다. 문자를 제거하는 동안 인덱스 이동을 방지하기 위해 인덱스를 내림차순으로 정렬합니다. 그런 다음 정렬된 인덱스를 반복하고 char_list에서 문자를 제거합니다. 마지막으로 나머지 문자를 결합하여 새 문자열을 만들고 반환합니다.

     

     

    my_string = "Forward, 9 days left"
    indices = [0, 9, 10, 12]
    result = erase_letters(my_string, indices)
    print(result)  # Output: "orward,  days lef"

     

    이 예에서 인덱스 0, 9, 10 및 12의 문자("F", "9", " " 및 "s")는 원래 문자열 "Forward, 9 days left"에서 제거되고 결과 문자열은 "orward, days lef"입니다.

    'TIL( Today I Learned)' 카테고리의 다른 글

    2023.7.25.화요일  (0) 2023.07.25
    2023.7.24.월요일. 100개  (0) 2023.07.24
    2023.7.22.토요일  (0) 2023.07.22
    2023.7.21.금요일  (0) 2023.07.21
    2023.7.20.목요일  (0) 2023.07.20
Designed by Tistory.