몸과 마음이 건전한 SW 개발자

Softeer level2 [21년 재직자 대회 예선] 비밀 메뉴 Python 본문

알고리즘

Softeer level2 [21년 재직자 대회 예선] 비밀 메뉴 Python

스위태니 2023. 7. 29. 17:39

문제 링크 : https://softeer.ai/practice/info.do?idx=1&eid=623 

 

Softeer

연습문제를 담을 Set을 선택해주세요. 취소 확인

softeer.ai

잘못된 코드

import sys
input = sys.stdin.readline

M, N, K = map(int, input().split())
secret = list(map(int, input().split()))
list_btn = list(map(int, input().split()))

index = 0
if M > N:
    print("normal")
else:
    for i in range(N):
        print(list_btn[i] == secret[index])
        if list_btn[i] == secret[index]:
            index += 1
            if index == M:
                print("secret")
                break
        else:
            index = 0
            if list_btn[i] == secret[index]:
                index += 1
                if index == M:
                    print("secret")
                    break
    else:
        print("normal")

 

입력값

4 5 3

3 3 1 3

3 3 3 1 3

 

결과값

True
True
False
False
True
normal

 

잘못된 점

위와 같은 코드로 할 경우 틀린 시점부터 0번 인덱스로 돌아가기 때문에

3 3 [3 1 3]

이런 식으로 검사 하게 된다.

 

정답코드

단순하게 Brute force 알고리즘을 적용해본다.

import sys
input = sys.stdin.readline

M, N, K = map(int, input().split())
secret = list(map(int, input().split()))
list_btn = list(map(int, input().split()))

if M <= N:
    for i in range(N):
        if i + M > N:
            print("normal")
            break
        length = 0
        for j in range(M):
            if secret[j] == list_btn[i+j]:
                length += 1
            else:
                break
        if length == M:
            print("secret")
            break
else:
    print("normal")

코드도 훨씬 간결해지고 쉽게 통과하는 모습