Create Opportunities

[알고리즘] 카드 뭉치 본문

알고리즘

[알고리즘] 카드 뭉치

kimjaeyoon 2023. 3. 2. 18:01

Lv. 1

내 풀이 (정답)

def solution(cards1, cards2, goal):
    for word in goal:
        if word == cards1[0]:
            cards1.pop(0)
        elif word == cards2[0]:
            cards2.pop(0)
        else:
            answer = 'No'; return answer
            
        if not cards1:
            cards1.append('temp')
        if not cards2:
            cards2.append('temp')
            
    answer = 'Yes'
    return answer

원하는  단어 배열(goal)을 순회하면서 cards1과 card2 리스트의 첫 번째 원소와 동일한지 확인하고, 동일하다면 해당 card의 원소를 삭제한다.

만약 둘 다 없다? 그러면 answer는 'No' 가 된다.

추가로 cards1과 cards2 리스트가 비어있다면 list index out of range가 되므로 그런 경우에 temp로 채워준다.

모범 풀이

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"

마찬가지로 goal을 순회.

if문에 and로 len > 0 조건 추가함.

 

출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges

'알고리즘' 카테고리의 다른 글

[알고리즘] 뒤에 있는 큰 수 찾기  (0) 2023.03.06
[알고리즘] 둘만의 암호  (1) 2023.03.06
[알고리즘] 숫자 변환  (0) 2023.03.02
[알고리즘] 덧칠하기  (0) 2023.03.02
[알고리즘] 대충 만든 자판  (0) 2023.03.02