๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Coding Test Practice

[Coding Test Practice] ์‹ ๊ทœ ์•„์ด๋”” ์ถ”์ฒœ

by Whiimsy 2021. 10. 30.

๐Ÿž ๋งํฌ

https://programmers.co.kr/learn/courses/30/lessons/72410

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์‹ ๊ทœ ์•„์ด๋”” ์ถ”์ฒœ

์นด์นด์˜ค์— ์ž…์‚ฌํ•œ ์‹ ์ž… ๊ฐœ๋ฐœ์ž ๋„ค์˜ค๋Š” "์นด์นด์˜ค๊ณ„์ •๊ฐœ๋ฐœํŒ€"์— ๋ฐฐ์น˜๋˜์–ด, ์นด์นด์˜ค ์„œ๋น„์Šค์— ๊ฐ€์ž…ํ•˜๋Š” ์œ ์ €๋“ค์˜ ์•„์ด๋””๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์—…๋ฌด๋ฅผ ๋‹ด๋‹นํ•˜๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. "๋„ค์˜ค"์—๊ฒŒ ์ฃผ์–ด์ง„ ์ฒซ ์—…๋ฌด๋Š” ์ƒˆ๋กœ

programmers.co.kr

 

๐Ÿž ์ ‘๊ทผ

๋”ฑํžˆ ์—†์Œ

์ •๊ทœ์‹ ์‚ฌ์šฉํ•ด๋ณด๊ธฐ

 

๐Ÿž ์ฝ”๋“œ

# ์ •๊ทœ์‹ ์‚ฌ์šฉ
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

# ์ •๊ทœ์‹ ๋ฏธ์‚ฌ์šฉ
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 ['-', '_', '.']:
            answer += c
    # 3
    while '..' in answer:
        answer = answer.replace('..', '.')
    # 4 (if-else๋ฌธ ํ•œ ์ค„์— ์ฒ˜๋ฆฌ)
    if answer[0] == '.':
        answer = answer[1:] if len(answer) > 1 else '.'
    if answer[-1] == '.':
        answer = answer[:-1]
    # 5
    if answer == '':
        answer = 'a'
    # 6
    if len(answer) > 15:
        answer = answer[:15]
        if answer[-1] == '.':
            answer = answer[:-1]
    # 7
    while len(answer) < 3:
        answer += answer[-1]
    return answer

 

๐Ÿž ํ›„๊ธฐ

์ •๊ทœ์‹ ์‚ฌ์šฉ์€ ์•„์ง ์–ด๋ ค์šด ๊ฒƒ ๊ฐ™๋‹ค.. ๋‚˜์ค‘์— ์‹œ๊ฐ„ ๋‚ด์„œ ๊ณต๋ถ€ํ•ด๋ด์•ผ ํ•  ๊ฒƒ ๊ฐ™๋‹ค.

 

์ •๊ทœ์‹์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ, ์™„์„ฑ ์ฝ”๋“œ๊ฐ€ ์ฒ˜์Œ ์ง  ์ฝ”๋“œ์™€ ๋น„์Šทํ•˜๊ธด ํ–ˆ๋Š”๋ฐ while๋ฌธ ์‚ฌ์šฉ์„ ๋ฌด์˜์‹์ ์œผ๋กœ ํ”ผํ•˜๊ณ  ์žˆ๋Š” ๊ฒƒ๊ณผ ๋ฐฐ์—ด์˜ ๋งˆ์ง€๋ง‰์„ arr[-1]๋กœ ์“ฐ๋Š” ๊ฒƒ์ด ์Šต๊ด€ํ™”๋˜์–ด ์žˆ์ง€ ์•Š๋‹ค๋Š” ๊ฒƒ์„ ์•Œ์•˜๋‹ค. ํ•„์š”ํ•  ๋•Œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์„ ๋งŒํผ ์ต์ˆ™ํ•ด์ ธ์•ผ ํ•  ๊ฒƒ ๊ฐ™๋‹ค.+ isalpha(), isdigit() ๋„ ์‚ฌ์šฉํ•œ ์ ์ด ๊ฑฐ์˜ ์—†๋‹ค ใ… 

 

์˜ค๋Š˜ ์ƒˆ๋กญ๊ฒŒ ์•Œ์•„๊ฐ€๋Š” ๊ฒƒ์€ if-else ๋ฌธ์„ ํ•œ ์ค„ ์•ˆ์— ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•˜๋Š” ๋ฒ•์ด๋‹ค.

 

ํ•œ ์ค„ ์•ˆ์— if-else ์‚ฌ์šฉํ•˜๊ธฐ :: ๊ฒฐ๊ณผ = A if ์กฐ๊ฑด else B

# answer์˜ ๊ธธ์ด๊ฐ€ 1๋ณด๋‹ค ํด ๊ฒฝ์šฐ answer[1:] ๋ฐ˜ํ™˜,
# answer์˜ ๊ธธ์ด๊ฐ€ 0,1์ธ ๊ฒฝ์šฐ '.' ๋ฐ˜ํ™˜
answer = answer[1:] if len(answer) > 1 else '.'

# ๊ฒฐ๊ณผ = A if ์กฐ๊ฑด else B