코딩테스트 연습 - 숫자 문자열과 영단어
숫자의 일부 자릿수가 영단어로 바뀌어졌거나, 혹은 바뀌지 않고 그대로인 문자열 s가 매개변수로 주어질 때, s가 의미하는 원래 숫자를 구하라.
문자열로 바뀐 부분이 정해진 형태이기 때문에 dictionary 형태로 저장하여 바뀐 문자열이 정해진 형태와 같을 경우 숫자로 변환하는 과정을 거쳤다.
def solution(s):
answer = ""
temp = ""
words = {'zero':0, 'one':1, 'two':2, 'three':3, 'four':4, 'five':5,
'six':6, 'seven':7, 'eight':8, 'nine':9}
for i in s:
if i.isalpha():
temp += i
elif i.isdigit():
answer += i
continue
if temp in words:
answer += str(words[temp])
temp = ""
return int(answer)
문자열을 하나씩 읽어서 검사하는 게 아니라 dictionary와 replace()를 사용하여 간단하게 정해진 규칙대로 변환하였다.
def solution(s):
words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six',
'seven', 'eight', 'nine']
for i in range(len(words)):
s = s.replace(words[i], str(i))
return int(s)