Stay Hungry Stay Foolish

프로그래머스 코딩테스트/Level 1

[Programmers] L1. 카드 뭉치 (Python)

dev스카이 2024. 11. 16. 15:08

[문제 링크] 👇

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr


풀이 방법

💡Queue 이용

  • cards1와 cards2를 각각 큐처럼 사용하여, 앞에서부터 단어를 꺼냄
  • goal 배열의 각 단어에 대해
    • 해당 단어가 cards1의 맨 앞에 있다면 cards1에서 제거
    • 그렇지 않고 cards2의 맨 앞에 있다면 cards2에서 제거
    • 두 곳 모두에 없다면 "No"를 반환
  • 모든 단어를 성공적으로 처리했다면 "Yes"를 반환

Solution

from collections import deque

def solution(cards1, cards2, goal):
    answer = "Yes"
    cards1 = deque(cards1)  # 큐 생성
    cards2 = deque(cards2)

    for i in goal:
        if cards1 and i == cards1[0]:
            cards1.popleft()
        elif cards2 and i == cards2[0]:
            cards2.popleft()
        else:
            answer = "No"
            break

    return answer

👩‍💻 회고

IndexError 가 뜬 이유

if cards1 and i in cards1[0]:
    cards1.popleft()
elif cards2 and i in cards2[0]:
    cards2.popleft()

 

카드 순서가 일치해야 하는데 리스트에 있는지 없는지만 판단했다. 그래서 card2가 비어있는데 0번째 인덱스에 있는지 찾으려고 하니 IndexError가 뜬 것이었다.