Python/Coding Test

[Coding Test] 숫자 문자열과 영단어

gangee 2023. 5. 27. 16:18

목차

    728x90
    반응형

    숫자 문자열과 영단어 : 2021 카카오 채용연계형 인턴십

    문제 설명

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

    다음은 숫자의 일부 자릿수를 영단어로 바꾸는 예시입니다.

    1478 → "one4seveneight"
    234567 → "23four5six7"
    10203 → "1zerotwozero3"
    이렇게 숫자의 일부 자릿수가 영단어로 바뀌어졌거나, 혹은 바뀌지 않고 그대로인 문자열 s가 매개변수로 주어집니다. s가 의미하는 원래 숫자를 return 하도록 solution 함수를 완성해주세요.

    숫자에 대응되는 영단어

    문제 풀이

    • 문자열 s에서 영단어와 대응되는 숫자를 replace를 이용해 변경해 answer에 저장
    • int를 이용해 answer을 정수형으로 변환하고 출력

    정답 코드

    def solution(s):
        answer = s.replace('zero', '0').replace('one', '1').replace('two','2').replace('three','3').replace('four','4').replace('five','5').replace('six','6').replace('seven','7').replace('eight','8').replace('nine','9')
    
        return int(answer)

    다른 사람 풀이

    num_dic = {"zero":"0", "one":"1", "two":"2", "three":"3", "four":"4", "five":"5", "six":"6", "seven":"7", "eight":"8", "nine":"9"}
    
    def solution(s):
        answer = s
        for key, value in num_dic.items():
            answer = answer.replace(key, value)
        return int(answer)
    • dictionary를 이용해 문제를 해결함
    * 이 문제는 프로그래머스 코딩테스트 연습 1단계 문제입니다.
    728x90
    반응형