52일차 문제

양진혁·2021년 12월 23일
0

문제풀이

expanded_form(12) # Should return '10 + 2'
expanded_form(42) # Should return '40 + 2'
expanded_form(70304) # Should return '70000 + 300 + 4'

def expanded_form(num):
    el = []
    a = len(str(num))-1
    for i in str(num):
        if i !="0":
            el.append(i+ "0"*a)
        a -=1
    return " + ".join(el)

먼저 빈 리스트를 만들어 준 후 만약 10이 있다고 하면 0이 1개 존재하기 때문에 문자열로 바꾼 숫자의 길이에서 1을 빼준다. 그게 0의 갯수이다. 그 다음 반복문을 통해서 i가 0이 아니면 문자열로 바꾼 앞자리 i와 0은 자릿수 만큼 곱한 후 더해주고 리스트에 추가해준다 그다음 a에 1을 뺀 후 반복해준다. 그리고 마지막에 join함수를 사용해 각 요소 사이 빈칸을 +로 바꿔준다.

두번째는
a -> 1
e -> 2
i -> 3
o -> 4
u -> 5

test.assert_equals(encode('hello'), 'h2ll4')
test.assert_equals(encode('How are you today?'), 'H4w 1r2 y45 t4d1y?')
test.assert_equals(encode('This is an encoding test.'), 'Th3s 3s 1n 2nc4d3ng t2st.')
test.assert_equals(decode('h2ll4'), 'hello')

모음은 숫자로 숫자는 모음으로 바꿔주는 코드를 encode와 decode 두가지를 만들어야 한다.

vowdic = {'a':'1', 'e':'2', 'i':'3', 'o':'4', 'u':'5'}
def encode(st):
    for i in vowdic:
        st = st.replace(i, vowdic[i])
    return st
def decode(st):
    for i,j in vowdic.items():
        st = st.replace(j, i)
    return st

vowdic이라는 딕셔너리를 만든 후 replace를 통해서 i를 vowdic[i] 즉 i를 키로 받는 벨류로 변화시켰고 디코드의 경우 items()를 통해 키 밸류값을 다 받은 후 replace를 통해 서로 값을 바꾸어 주었다.

0개의 댓글