[Python#55] 카드뭉치

Gi Woon Lee·2024년 9월 9일
0

Python

목록 보기
12/13

카드뭉치

문제 이해

카드뭉치 1과 2에서 순차적으로 카드를 뽑아 원하는 goal 을 만들 수 있으면 Yes,
만들 수 없으면 No를 리턴하라!

방법1: 매뉴얼로 하나씩 넣어주기

cards1 = ["i", "drink", "water"]
cards2 = ["want", "to"]
goal = ["i", "want", "to", "drink", "water"]

def solution(cards1, cards2, goal):
    answer = ""
    index1 = 0
    index2 = 0
    A = []

    for i in goal:
        if i == cards1[index1]:
            A.append(cards1[index1])
            if index1 < (len(cards1)-1):
                index1 += 1 

        elif i == cards2[index2]:
            A.append(cards2[index2])
            if index2 < (len(cards2)-1):
                index2 += 1 
            
        else:
            break

    if A == goal:
        answer += "Yes"
    else:
        answer += "No"

    return answer

solution(cards1, cards2, goal)

if와 elif로 진행을 two point로 잡아 하나씩 추가해나가는 방법이다.

방법2: pop()을 통해 한번씩 빼주기 (🔥best!)

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"

and연산자를 통해 복수의 조건을 점검하고, pop메서드를 통해 아예 점검 대상의 index를 0으로 고정하는 기발한 아이디어!

0개의 댓글