[프로그래머스] 카드 뭉치

kiki·2024년 1월 14일
0

프로그래머스

목록 보기
65/76

문제 링크

https://school.programmers.co.kr/learn/courses/30/lessons/159994

문제 설명

  • 문자열로 이루어진 배열 cards1, cards2와 원하는 단어 배열 goal이 매개변수로 주어질 때, cards1과 cards2에 적힌 단어들로 goal를 만들 있다면 "Yes"를, 만들 수 없다면 "No"를 return
  • 원하는 카드 뭉치에서 카드를 순서대로 한 장씩 사용합니다.
  • 한 번 사용한 카드는 다시 사용할 수 없습니다.
  • 카드를 사용하지 않고 다음 카드로 넘어갈 수 없습니다.
  • 기존에 주어진 카드 뭉치의 단어 순서는 바꿀 수 없습니다.

1차 시도

def solution(cards1, cards2, goal):
    for i in goal:
        if i in cards1:
            if i!=cards1.pop(0):
                return 'No'
        if i in cards2:
            if i!=cards2.pop(0):
                return 'No'
    return 'Yes'

if문은 중첩으로 쓰지말고 and연산자로 연결하자
그리고 문제에서 cards1과 cards2에 중복되는 문자는 없다고 했지만 if, elif로 묶는게 효율적이고 의미있는 코드다.

2차 시도

def solution(cards1, cards2, goal):
    for i in goal:
        if i in cards1 and i!=cards1.pop(0):
            return 'No'
        elif i in cards2 and i!=cards2.pop(0):
            return 'No'
    return 'Yes'

3차 시도 - 다른 사람 풀이 보고

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

정리

  • if문은 이중으로 쓸 필요 없이 and로 연결해라
  • 이 문제와 같은 경우는 if, elif로 써라. 더 효율적인 코드다.

0개의 댓글