[2021 카카오 코딩테스트] 신규 아이디 추천 - 파이썬

2021. 11. 22. 05:00네카라쿠배 취준반 - 프로그래머스 문제 풀이

0. 자세한 설명은 YouTube 영상으로

 

1-1. 정규표현식을 활용하지 않는 solution

def solution(new_id):
    answer = ''
    # 1
    new_id = new_id.lower()
    # 2
    for c in new_id:
        if c.isalpha() or c.isdigit() or c in "-_.":
        # if c.isalnum() or c in "-_.":
            answer += c
    # 3
    while '..' in answer:
        answer = answer.replace('..', '.')
    # 4
    if answer and answer[0] == '.':
    # if answer[0:1] == '.':
        answer = answer[1:]
    if answer and answer[-1] == '.':
    # if answer[-1:0] == '.':
        answer = answer[:-1]
    # 5
    if answer == '':
        answer = 'a'
    # 6
    answer = answer[:15]
    if answer[-1] == '.':
        answer = answer[:-1]
    print(answer)
    # 7
    while len(answer) < 3:
        answer += answer[-1]
    
    return answer

print(solution("...!@BaT#*..y.abcdefghijklm"))

 

 

 

 

 

 

 

1-2. 정규표현식을 활용한 solution

import re

def solution(new_id):
    # 1
    answer = new_id.lower()
    #2
    answer = re.sub('[^a-z0-9\-_.]', '', answer)
    #3
    answer = re.sub('\.+', '.', answer)
    #4
    answer = re.sub('^[.]|[.]$', '', answer)
    #5
    if answer == '':
        answer ='a'
    #6
    answer = answer[:15]
    answer = re.sub('[.]$', '', answer)
    #7
    while len(answer) < 3:
        answer += answer[-1]
    return answer

print(solution("...!@BaT#*..y.abcdefghijklm"))
  • YouTube 영상에 자세한 내용을 정리했으니 참고하세요.