๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Programming/Coding Test

[Level 2] ๊ด„ํ˜ธ ๋ณ€ํ™˜ (Python)

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๊ด„ํ˜ธ ๋ณ€ํ™˜

์นด์นด์˜ค์— ์‹ ์ž… ๊ฐœ๋ฐœ์ž๋กœ ์ž…์‚ฌํ•œ ์ฝ˜์€ ์„ ๋ฐฐ ๊ฐœ๋ฐœ์ž๋กœ๋ถ€ํ„ฐ ๊ฐœ๋ฐœ์—ญ๋Ÿ‰ ๊ฐ•ํ™”๋ฅผ ์œ„ํ•ด ๋‹ค๋ฅธ ๊ฐœ๋ฐœ์ž๊ฐ€ ์ž‘์„ฑํ•œ ์†Œ์Šค ์ฝ”๋“œ๋ฅผ ๋ถ„์„ํ•˜์—ฌ ๋ฌธ์ œ์ ์„ ๋ฐœ๊ฒฌํ•˜๊ณ  ์ˆ˜์ •ํ•˜๋ผ๋Š” ์—…๋ฌด ๊ณผ์ œ๋ฅผ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค. ์†Œ์Šค๋ฅผ ์ปด๏ฟฝ

programmers.co.kr

 

def is_correct(b):
    stack = []
    
    for i in b:
        if i == '(':
            stack.append(i)
        elif stack:
            stack.pop()
            
    return not stack

def detach(b):
    lst_b = list(b)
    
    cnt_l = 0
    cnt_r = 0
    
    for i in b:
        if i == '(':
            cnt_l += 1
        else:
            cnt_r += 1
            
        if cnt_l == cnt_r:
            break
            
    u = b[:cnt_l+cnt_r]
    v = b[cnt_l+cnt_r:]
            
    return ''.join(u), ''.join(v)

def reverse(u):
    lst_u = list(u)
    
    return ''.join([')' if b == '(' else '(' for b in u[1:-1]])

def recursion(p):
    if p == '':
        return p
    
    u, v = detach(p)
    
    if is_correct(u):
        return u + recursion(v)
    else:
        return '(' + recursion(v) + ')' + reverse(u)
    
def solution(p):
    return p if is_correct(p) else recursion(p)

 

โ–ท ์ด ๋ฌธ์ œ์˜ ํ•ต์‹ฌ์€ ๋ณ€ํ™˜๊ณผ์ •์˜ ๊ฐ ์ˆ˜ํ–‰๊ณผ์ •์„ ํ•จ์ˆ˜ํ™”ํ•˜์—ฌ ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด๋‹ค. ๋”ฐ๋ผ์„œ ๋ฌธ์ž์—ด์ด ์˜ฌ๋ฐ”๋ฅธ์ง€ ํ™•์ธํ•˜๋Š” is_correct ํ•จ์ˆ˜, ๋ฌธ์ž์—ด์„ ๋ถ„๋ฆฌํ•˜๋Š” detach ํ•จ์ˆ˜, ๋ฌธ์ž์—ด์„ ๋’ค์ง‘๋Š” reverse ํ•จ์ˆ˜, ๋งˆ์ง€๋ง‰์œผ๋กœ ์žฌ๊ท€๋ฅผ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ๋„๋ก recursion ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์—ˆ๋‹ค.

 

โ–ท ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค ๋•Œ, ์ค‘์š”ํ•œ ์ ์€ ๋ฉˆ์ถ”๋Š” ์ง€์ ์„ ์„ค์ •ํ•˜๋Š” ๊ฒƒ์ธ๋ฐ, ๋ฌธ์ œ์˜ ์„ค๋ช…์„ ๋”ฐ๋ผ๊ฐ€๋ฉฐ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋ฉด ์•Œ์•„์„œ ์„ค์ •ํ•˜๋Š” ์ž์‹ ์˜ ๋ชจ์Šต์„ ๋ณด๊ฒŒ ๋  ๊ฒƒ์ด๋‹ค. recursion ํ•จ์ˆ˜๋ฅผ ๋ฉˆ์ถ”๊ฒŒ ํ•˜๋Š” ์ฝ”๋“œ๋Š” if p == '':  return p ์ด๋‹ค.

 

โ–ถ for i in [String] ๋ฌธ์—์„œ i๋Š” String์— ํฌํ•จ๋œ ๊ฐ ๊ธ€์ž์— ๋Œ€ํ•ด ํ• ๋‹นํ•œ๋‹ค.

 

โ–ถ not [True/False] ๋Š” True/False์˜ ๋ฐ˜๋Œ€ ๊ฒฐ๊ณผ๋กœ ๋งŒ๋“ค์–ด์ค€๋‹ค.

 

โ–ถ ๋ฆฌ์ŠคํŠธ์— ํฌํ•จ๋œ ๋ฌธ์ž๋ฅผ ํ•˜๋‚˜์˜ ๋ฌธ์ž์—ด๋กœ ํ•ฉ์น˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ''.Join([List]) ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.

'Programming > Coding Test' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Level 2] H-Index (Python)  (0) 2020.10.05
[Level 2] ์œ„์žฅ (Python)  (0) 2020.09.30
[Level 2] ์‚ผ๊ฐ ๋‹ฌํŒฝ์ด (Python)  (0) 2020.09.29
[Level 2] ์นดํŽซ (Python)  (0) 2020.09.24
[Level 2] ๋‹ค์Œ ํฐ ์ˆซ์ž (Python)  (0) 2020.09.24