글모음

[프로그래머스] 숫자 문자열과 영단어 [level1, Python] 본문

카테고리 없음

[프로그래머스] 숫자 문자열과 영단어 [level1, Python]

Nova_61 2021. 7. 22. 14:19
728x90
반응형

[코드 1] regex 정규 표현식 사용

import re

def solution(s):
    num_dic = {'zero' : '0', 'one' : '1', 'two' : '2','three' : '3', 'four' : '4','five' : '5', 'six' : '6', 'seven' : '7', 'eight' : '8', 'nine' : '9'}
    ans = ''
               
    option = re.compile("zero|one|two|three|four|five|six|seven|eight|nine|\d")
    nums = option.findall(s)

    for n in nums:
        try : 
            n = num_dic[n]
            ans += n
        except : 
            ans += n
    return int(ans)

특정 문자들을 찾아낸다는 생각에 꽂혀서 정규 표현식만 생각을 했다.

더 간단한 replace 함수는 생각도 못했음 ㅋㅋ

정규 표현식은 계속 헷갈려서 날 잡아서 정리해야겠다.

 

[코드 2] 정규 표현식 사용 X -> 리스트, replace 함수 이용

def solution(s):
    nums = ['zero','one','two','three','four','five','six','seven','eight','nine']
    for i in range(len(nums)):
        s = s.replace(nums[i],str(i))
    return int(s)

 

[코드3] 정규 표현식 사용 X -> dictionary, replace 함수 이용

def solution(s):
    num_dic = {'zero' : '0', 'one' : '1', 'two' : '2','three' : '3', 'four' : '4','five' : '5', 'six' : '6', 'seven' : '7', 'eight' : '8', 'nine' : '9'}
    
    for key, value in num_dic.items():
        s = s.replace(key,value)
    return int(s)
728x90
반응형
Comments