본문 바로가기

알고리즘/카카오 EASY

숫자 문자열과 영단어 (Level 1)

문제

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

 

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

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

programmers.co.kr

 

내 풀이

 

  1. table의 인덱스를 사용하려고 리스트 1개를 만들었다.
  2. s의 원소가 숫자일 때는 바로 answer에 추가하고, 알파벳일 때는 원소를 임의의 변수에 저장한 다음 table에 있는 단어인지 확인하도록 하였다.

 

def solution(s):
    answer = ''
    table = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
    tmp, idx = '', 0
    for i in range(len(s)):
        if s[idx].isdigit(): answer += s[idx]
        if s[idx].isalpha():
            tmp += s[idx]
            if tmp in table:
                answer += str(table.index(tmp))
                tmp = ''
        idx += 1
        
    return int(answer)

 

다른 풀이

 

  1. 영어와 숫자를 문자열 형태로 num_dic라는 dictionary에 저장하였다.
  2. answer에서 key(영어) 부분을 전부 value(숫자)로 바꾸기 위해 문자열을 변경하는 함수인 replace 함수를 사용하였다.

 

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)

 

총평

replace 하나만으로 정말 간단하게 코드를 작성할 수 있는 것을 배웠다.

파이썬 함수는 양파같은 놈들이다. 까도 까도 새로운 게 나오는 느낌이랄까.

'알고리즘 > 카카오 EASY' 카테고리의 다른 글

크레인 인형뽑기 게임 (Level 1)  (0) 2022.06.24
키패드 누르기 (Level 1)  (0) 2022.05.26
오픈채팅방 (Level 2)  (0) 2022.05.24
문자열 압축 (Level 2)  (0) 2022.05.23
신규 아이디 추천 (Level 1)  (0) 2022.05.23