쉽고 깔끔하게
[프로그래머스/python3] Level 1 숫자 문자열과 영단어 문제풀이 본문
728x90
반응형

문제
https://programmers.co.kr/learn/courses/30/lessons/81301
코딩테스트 연습 - 숫자 문자열과 영단어
네오와 프로도가 숫자놀이를 하고 있습니다. 네오가 프로도에게 숫자를 건넬 때 일부 자릿수를 영단어로 바꾼 카드를 건네주면 프로도는 원래 숫자를 찾는 게임입니다. 다음은 숫자의 일부 자
programmers.co.kr
숫자의 일부 자릿수가 영단어로 바뀌어졌거나, 혹은 바뀌지 않고 그대로인 문자열 s가 매개변수로 주어집니다. s가 의미하는 원래 숫자를 return 하도록 solution 함수를 완성해주세요.
<풀이>
문제를 읽고 다음과 같은 해결 방법을 떠올렸다.
- 딕셔너리를 이용하여 key-value 쌍으로 서로 대응하는 데이터를 빠르게 찾기
- 딕셔너리의 key-value 쌍을 얻기 위해 items()라는 함수 사용하기
- 문자열을 변경(치환)해주기 위해 replace() 함수 사용하기
1. 딕셔너리를 이용하여 key-value 쌍으로 서로 대응하는 데이터를 빠르게 찾기
num_dic = {'zero':'0', 'one':'1', 'two':'2', 'three':'3', 'four':'4', 'five':'5', 'six':'6', 'seven':'7', 'eight':'8', 'nine':'9'}
영단어를 숫자로 바꾸어(영단어 → 숫자) 결과로 출력하기 때문에 key 값에 영단어를, value 값에 숫자를 넣어주었다.
2. 딕셔너리의 key-value 쌍을 얻기 위해 items()라는 함수 사용하기
for i in num_dic.items():
for 문을 수행할 때 각자의 key-value 쌍을 얻기 위해 앞에서 선언한 num_arr에 items() 함수를 사용하였다.
3. 문자열을 변경(치환)해주기 위해 replace() 함수 사용하기
answer = answer.replace(i[0], str(i[1]))
i[0] 즉, key 값을 i[1] value 값으로 바꿔주는 구문이다.
※ replace() 형식
str.replace("찾을 값", "바꿀 값", [바꿀 횟수])
<정답>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def solution(s): | |
answer = s | |
num_dic = {'zero':'0', 'one':'1', 'two':'2', 'three':'3', 'four':'4', 'five':'5', 'six':'6', 'seven':'7', 'eight':'8', 'nine':'9'} | |
for i in num_dic.items(): | |
answer = answer.replace(i[0], str(i[1])) | |
return int(answer) |
※ return int(answer)을 수행하는 이유는 answer이 숫자가 아닌 문자형으로 저장되어 있기 때문이다.
► 이를 수행하지 않으면 "123"으로 수행된다.
728x90
반응형
'Algorithm > Programmers' 카테고리의 다른 글
[프로그래머스/python] Level 1 1주차_부족한 금액 계산하기 문제풀이 (0) | 2021.09.17 |
---|---|
[프로그래머스/python3] Level 1 음양 더하기 문제풀이 (0) | 2021.09.17 |
[프로그래머스/python3] Level 2 튜플 문제풀이 (0) | 2021.09.16 |
[프로그래머스/python3] Level 1 모의고사 문제풀이 (0) | 2021.03.02 |
[프로그래머스/python3] Level 1 체육복 문제풀이 (0) | 2021.02.26 |