코딩테스트 연습

카드 뭉치

코딩초보ran 2023. 11. 15. 10:23

 

 

문제 풀이1

def solution(cards1, cards2, goal):
    
    dict={}
    for i, c1 in enumerate(cards1):
        dict[c1] = i
    for j, c2 in enumerate(cards2):
        dict[c2] = j
    
    for idx in range(len(goal)-1):

        if dict[goal[idx]] > dict[goal[idx+1]]:
            answer='No'
        else:
            answer='Yes'
    
    return answer

 

채점결과1

 

어떤 부분에서 틀린 거였냐면, 나는 goal 문자열 index(카드 기준)가 뒤 index랑 비교했을 때 같거나 커야한다고 생각했음. 그러니까 앞, 뒤 문자열 인덱스를 비교했을 때 뒤에 있는 index가 작으면 break를 하고 No를 반환하는 것으로 풀었음.

 

근데 현재 index보다 다음 index가 작을 수도 있음!

예를 들어서,

cards1 = [i, want, to, drink]

cards2 = [water] 

goal = [i, want, to, drink, water]

라고 한다면, goal 의 문자열을 cards1, cards2 에서 찾았을 때 index를 봤을 때

 

i want to  drink water
0 1 2 3 0

 

이렇게 index가 나열될 수 있음.

그래서 이런 경우엔 Yes를 반환하는 게 정답이지만 내 풀이에서는 No를 반환하기 때문에 틀린 것.

 

 

 

문제 풀이2

def solution(cards1, cards2, goal):
    
    for _ in range(len(goal)):
        cards1+='1'
        cards2+='2'

    answer='Yes'
    for g in goal:

        if (g == cards1[0]):
            cards1.pop(0)
        elif  (g == cards2[0]):
            cards2.pop(0)
        else:
            answer='No'
    
    return answer

 

cards1, cards2 에 goal 길이만큼 +1,+2 해주는 코드를 왜 추가했냐면,

만약에 cards1 길이가 1이라서 pop(0)으로 0번째 index원소를 빼면 cards1은 빈 list가 됨

그 상태에서 for문을 돌게 되면 빈 list에 0번째를 추출하려고 하니까 IndexError: list index out of range 에러가 난다!

그래서 그냥 goal의 길이만큼 list를 늘려줬다....

 

채점결과2

 


다른 사람 풀이

def solution(cards1, cards2, goal):
    for g in goal:
        if len(cards1) > 0 and g == cards1[0]:
            cards1.pop(0)       
        elif len(cards2) >0 and g == cards2[0]:
            cards2.pop(0)
        else:
            return "No"
    return "Yes"

 

내 문제풀이2번에서 처음엔 이렇게 짰었는데... 왜 안 됐었지...?

하여튼, cards의 길이를 먼저 확인하고, pop을 하면 되겠다!

cards 길이를 늘려주는 것보다 훨씬 낫다!!

 

다른 사람 풀이 채점 결과