숫자 문자열과 영단어

yongju·2022년 11월 3일
0

Programmers

목록 보기
6/23
post-thumbnail

프로그래머스 [정답률 66%]



문제 정리
사용한 파라미터:
s(string) : 입력으로 받은 문자와 숫자가 섞인 문자열
num_eng(dictionary) : {숫자:"문자"}

  • num_eng value가 s의 문자열에 속해있다면, num_eng의 키값을 출력
    사용함수 : replace
    코드
def solution(s):
    num_eng={0:"zero",1:"one", 2:"two", 3:"three", 4:"four", 5:"five", 6:"six", 7:"seven", 8:"eight", 9: "nine"}

    for i in range(len(num_eng)):#0~9
        if num_eng[i] in s or str(i) in s:#문자열(딕셔너리의 밸류)이 s에 있는지
            s=s.replace(num_eng[i],str(i))

    return int(s)

코드 설명

    num_eng={0:"zero",1:"one", 2:"two", 3:"three", 4:"four", 5:"five", 6:"six", 7:"seven", 8:"eight", 9: "nine"}

숫자는 키, 단어는 밸류인값으로 이루어진 딕셔너리 만들기

    for i in range(len(num_eng)):#0~9
        if num_eng[i] in s or str(i) in s:#문자열(딕셔너리의 밸류)이 s에 있는지
            s=s.replace(num_eng[i],str(i))

만약, 단어가 문자열s에 있다면 기존의 단어대신 키값으로 대체(replace)

    return int(s)

s는 문자열이기 때문에 출력형식에따라 int로 변환

프로그래머스 코드 리뷰

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)

딕셔너리 함수인 items()를 사용하여 키값과 밸류를 받음. replace를 사용하여 단어인 key대신에 숫자인 value를 넣어줌. 출력형식에 맞추어 int로 변환.
👍딕셔너리의 특징을 살림!

profile
AI dev

0개의 댓글