상세 컨텐츠

본문 제목

[백준/파이썬]5430 AC

알고리즘 문제풀이

by 한백인데용 2023. 7. 26. 00:44

본문

728x90
반응형

https://www.acmicpc.net/problem/5430

 

5430번: AC

각 테스트 케이스에 대해서, 입력으로 주어진 정수 배열에 함수를 수행한 결과를 출력한다. 만약, 에러가 발생한 경우에는 error를 출력한다.

www.acmicpc.net

 

문제

백준5430 AC

삽질 엄청한 문제다.

 

문제가 제목값 하는 문제다.

 

나에게 도움이 된 반례는

 

1

D

1

[]

정답 : error

 

1

R

1

[]

정답 : []

오답

반례를 찾아보며 여러번 수정한 끝에 맞출 수 있었다.

 

코드 길이를 보면 알겠지만 반례를 찾아가며 코드가 한줄한줄 늘어났고, 늘어난 코드에서 필요없는 부분들을 지우다 보니 이렇게 됐다.

 

저기 제일 긴 코드도 내가 찾아본 모든 반례가 통과하긴 했다.

 

from collections import deque
import sys
import re
input = sys.stdin.readline

num = int(input().rstrip())

for _ in range(num) :
    command = input().rstrip()
    n = int(input().rstrip())
    s = input().rstrip()
    if len(s) == 2 :
        continueTF = False
        for c in command :
            if c == 'D' :
                print('error')
                continueTF = True

        if not continueTF :
            print('[]')
        else : 
            continue
    else :
        que = deque(map(int, s[1:len(s)-1].split(',')))
        try :
            reverseTF = False
            for c in command :
                if c == 'D' and not reverseTF:
                    que.popleft()
                elif c == 'D' and reverseTF :
                    que.pop()
                elif c == 'R' :
                    if not reverseTF :
                        reverseTF = True
                    else :
                        reverseTF = False
            if len(que) != 0 :
                if reverseTF :
                    que = list(map(str, que))[::-1]
                    ans = ','.join(que)
                    print('[{}]'.format(ans))
                else :
                    que = list(map(str, que))
                    ans = ','.join(que)
                    print('[{}]'.format(ans))
            else :
                print('[]')
        except :
            print('error')

이게 제일 긴 코드인데, 아직도 이게 왜 통과 못했는지 모르겠다. 어디가 문제인지. 

 

아마 처음에 입력된 리스트가 비어있을때 처리하는 부분(if len(s)==2이 부분)이 문제인것 같긴 하다. 그냥 반례에 맞게만 수정하다 보니 반례외에 다른 문제점이 있었던것 같다.

 

정답

from collections import deque

num = int(input())

for _ in range(num) :
    command = input()

    n = int(input().rstrip())
    s = input()
    if n == 0 :
        que = deque()
    else :
        que = deque(map(int, s[1:-1].split(',')))
    try :
        reverseTF = False
        for c in command :
            if c == 'D' and not reverseTF:
                que.popleft()
            elif c == 'D' and reverseTF :
                que.pop()
            elif c == 'R' :
                reverseTF = not reverseTF

        if reverseTF :
            que = list(map(str, que))[::-1]
            ans = ','.join(que)
            print('[{}]'.format(ans))
        else :
            que = list(map(str, que))
            ans = ','.join(que)
            print('[{}]'.format(ans))

    except :
        print('error')

필요 없는 부분은 싹 지우고 깔끔한 코드가 됐다. 

 


반례에 맞게 수정하는것도 중요하지만 문제를 맞추기 위해 어거지로 풀이하는건 지양해야겠다..

 

728x90
반응형

관련글 더보기