괄호 변환
이번 문제는 코딩 문제가 아니라 한국어 능력 평가 같은 시험이었다.
첫 번째 코드
def solution(p):
    answer = ''
    answer=f(p,'')
    return answer
def f(p,result):
    print('this is start')
    u=[]
    v=[]
    check=0
    check1=True
    check2=True
    if len(p)==0:
        print('1')
        return ''
    for i in p:
        if check1:
            if i=='(':
                u.append(i)
                check+=1
            else:
                u.append(i)
                check-=1
                if check<0:
                    check2=False
        else:
            v.append(i)
        if check==0:
            check1=False
    if check2:
        print('2',u,v,result)
        result=result+''.join(u)
        print('result',result)
        return result+f(v,'')
    else:
        print('3',u,v)
        temp='('
        print('temp',temp)
        u.pop(0)
        u.pop(-1)
        print('u',u)
        temp2=''
        for i in u:
            if i=='(':
                temp2=temp2+')'
            else:
                temp2=temp2+'('
        temp3=f(v,'')
        temp=temp+temp3+')'+temp2
        return temp
- 매우매우 더럽다.
- 하지만 잘 보면, f함수의 result 값이 계속 ‘‘로 빈 문자열만 들어가는 것이 보인다.
- 따라서 solution 함수 하나로도 충분히 재귀 함수로 만들 수 있다는 말이다.
def solution(p):
    answer = ''
    u=[]
    v=[]
    check=0
    check1=True
    check2=True
    if len(p)==0:
        return ''
    for i in p:
        if check1:
            if i=='(':
                u.append(i)
                check+=1
            else:
                u.append(i)
                check-=1
                if check<0:
                    check2=False
        else:
            v.append(i)
        if check==0:
            check1=False
    if check2:
        result=''.join(u)
        return result+solution(v)
    else:
        temp='('
        u.pop(0)
        u.pop(-1)
        temp2=''
        for i in u:
            if i=='(':
                temp2=temp2+')'
            else:
                temp2=temp2+'('
        temp3=solution(v)
        temp=temp+temp3+')'+temp2
        answer=temp
    return answer
- 하나의 재귀 함수로 합쳐주었다.