Algorithm

카드 뭉치 / 프로그래머스

김예나 2025. 2. 24. 10:06

 

첫 번째 시도

  • IndexError: list index out of range 직면
  • cards1 또는 cards2가 빈 리스트인 경우에 cards1[0]처럼 참조하면 오류가 나기 때문임
  • cards1[0]과 같이 참조하기 전에 길이를 먼저 체크하도록 변경해야 함
def solution(cards1, cards2, goal):
    answer = "Yes"
    while(len(cards1) or len(cards2)):
        if len(goal) == 0:
            break
        elif cards1[0] == goal[0] and len(cards1) > 0:
            cards1.pop(0)
            goal.pop(0)
        elif cards2[0] == goal[0] and len(cards2) > 0:
            cards2.pop(0)
            goal.pop(0)
        else:
            answer = "No"
            break
            
    return answer

 

 

정답

  • 리스트를 참조하기 전에 길이를 먼저 체크하도록 변경
def solution(cards1, cards2, goal):
    answer = "Yes"
    while(len(cards1) or len(cards2)):
        if len(goal) == 0:
            break
        elif len(cards1) > 0 and cards1[0] == goal[0]:
            cards1.pop(0)
            goal.pop(0)
        elif len(cards2) > 0 and cards2[0] == goal[0]:
            cards2.pop(0)
            goal.pop(0)
        else:
            answer = "No"
            break
            
    return answer