생각과 고민이 담긴 코드

프로그래머스 - 숫자 문자열과 영단어 (2021 카카오 채용연계 인턴십) / Level 1 본문

Algorithm/프로그래머스

프로그래머스 - 숫자 문자열과 영단어 (2021 카카오 채용연계 인턴십) / Level 1

0_Hun 2021. 12. 5. 12:37

문제 : https://programmers.co.kr/learn/courses/30/lessons/81301

 

코딩테스트 연습 - 숫자 문자열과 영단어

네오와 프로도가 숫자놀이를 하고 있습니다. 네오가 프로도에게 숫자를 건넬 때 일부 자릿수를 영단어로 바꾼 카드를 건네주면 프로도는 원래 숫자를 찾는 게임입니다. 다음은 숫자의 일부 자

programmers.co.kr

 

풀이

def solution(s):
    
    nums = [str(i) for i in range(10)]
    en_nums = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
    word = []
    s = list(s)
    i = 0
    
    while True:
        
        if "".join(word) in en_nums:
                s.insert(i, str(en_nums.index("".join(word))))
                word = []
                i += 1
        elif s[i] not in nums:
            word.append(s[i])
            s.remove(s[i])
        else:
            i += 1
        
        if i >= len(s):
            if word:
                s.insert(i, str(en_nums.index("".join(word))))
                break
            else:
                break
    
    return int("".join(s))

쉬운 문제였다. 영어단어로 된 문자열을 해당하는 숫자로 바꿔주는 문제이다.

다만 리스트를 순회하면서 삽입, 삭제를 하기 때문에 index를 세심하게 체크해야 했다.

 

+ 다른 사람들의 풀이를 보니 replace 함수를 사용하여 더 쉽게 풀 수 있었다.

built-in 함수들을 더 숙달시켜야겠다.