공부/코딩테스트

[프로그래머스] 신규 아이디 추천(파이썬)

ghhong 2021. 12. 25. 17:52

나의 답 : 

def solution(new_id):
    new_id = new_id.lower()
    for i in new_id:
        if i in '~!@#$%^&*()=+[{]}:?,<>/':
            new_id = new_id.replace(i,'')
    while('..' in new_id):
        new_id = new_id.replace('..','.')
    l=len(new_id)
    if(l>0):
        if(new_id[0]=='.'):
            new_id=new_id[1:]
    l=len(new_id)
    if(l>0):
        if(new_id[l-1]=='.'):
            new_id=new_id[:-1]
    if(len(new_id) == 0):
        new_id='a'
    if(len(new_id)>=16):
        new_id = new_id[:15]
        if(new_id[-1]=='.'):
            new_id=new_id[:14]
    while(len(new_id)<=2):
        new_id=new_id+new_id[-1]
    
    return new_id

 

다른 사람의 답 :

import re

def solution(new_id):
    st = new_id
    st = st.lower()
    st = re.sub('[^a-z0-9\-_.]', '', st)
    st = re.sub('\.+', '.', st)
    st = re.sub('^[.]|[.]$', '', st)
    st = 'a' if len(st) == 0 else st[:15]
    st = re.sub('^[.]|[.]$', '', st)
    st = st if len(st) > 2 else st + "".join([st[-1] for i in range(3-len(st))])
    return st

 

'..' 바꾸는 부분에서 정규표현식쓰려다가 말았는데..