눈송이의 개발생활
[Programmers Lv.1]숫자 문자열과 영단어 (Python) 본문
문제
https://programmers.co.kr/learn/courses/30/lessons/81301
내 코드
def solution(s):
dict = {"zero": 0, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8,
"nine": 9}
answer = ""
temp = ""
arr = list(s)
for i in range(len(arr)):
if arr[i].isdigit():
answer += arr[i]
temp = ""
else:
temp += arr[i]
if temp in dict:
answer += str(dict[temp])
temp = ""
return int(answer)
다른 사람 풀이
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)
해결 방법
딕셔너리를 이용해서 풀어야 하는 것은 문제를 보자마자 바로 깨닳았다.
저번에 문제를 풀면서 python에서는 문자열을 바꿀 수 없다는 것을 배워서 이번에는 새로운 문자열을 만드는 방법을 선택했다.
isdigit() 함수로 숫자인지 아닌지 판단하고 숫자면 딕셔너리에서 찾아 문자열을 바꿨다.
리스트에서 알파벳 하나씩 보기 때문에 temp는 그 알파벳들을 모아서 단어로 보기 위해 만든 변수이다.
다른 사람이 푼 정답을 보니, replace() 함수를 사용해서 문자열의 내용을 바꿔주었다.
replace함수로 문자열 내부를 교체할 수 있지만, index로 참조해서 바꿀 수는 없는거같다.
✅ 파이썬 공부하자... 언어를 잘 알아야 문제를 금방금방 풀 수 있다.
'Algorithm > Programmers' 카테고리의 다른 글
[Programmers Lv.1]크레인 인형 뽑기 (Python) (0) | 2022.03.26 |
---|---|
[Programmers Lv.1]키패드 누르기 (Python) (0) | 2022.03.23 |
[Programmers Lv.1]콜라츠 추측 & 최대공약수와 최소공배수 (Python) (0) | 2022.03.10 |
[Programmers Lv.1]정수 제곱근 판별 & 정수 내림차순으로 배치하기 (Python) (0) | 2022.03.10 |
[Programmers Lv.1]짝수와 홀수 & 하샤드 수 (Python) (0) | 2022.03.07 |
Comments