Algorithm
프로그래머스
Python
숫자 문자열과 영단어

숫자 문자열과 영단어

숫자 문자열과 영단어 (opens in a new tab)

내 풀이

맞추기는 했는데 코드가 더럽다...

def solution(s):
  n_hash = {
    '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9
  }
  a_hash = {
    "zero" : 0, 'one': 1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9
  }
  s_list = list(s)
  ans = ""
  cur_val = ""
  while s_list :
    cur_val += s_list.pop(0)
    if cur_val in n_hash :
      ans += str(n_hash[cur_val])
      cur_val = ""
    elif cur_val in a_hash :
      ans += str(a_hash[cur_val])
      cur_val = ""
  return int(ans)

다른 사람 풀이

dictionary 활용

어느 누가 출저인지는 모르겠지만 약간 정석적인 답인 느낌이다.

def solution(s):
  answer = s
  num_s = {'zero':0, 'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'six':6, 'seven':7, 'eight':8, 'nine':9}
 
  for key in num_s.keys():
    answer = answer.replace(key[0], str(num_s[key]))
 
  return int(answer)

index 활용

def solution(s):
  answer = s
  num_s = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
 
  for i, key in enumerate(num_s) :
    answer = answer.replace(key[0], str(i))
 
  return int(answer)

배운점

replace() 함수에 관해서 배우는 계기가 되었다.(알고는 있었지만 안쓴듯)