๐Ÿงฉ Algorithm/[Programmers] Level 1

[Programmers] L1. ์นด๋“œ ๋ญ‰์น˜ (Python)

devCloud 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๊ฐ€ ๋œฌ ๊ฒƒ์ด์—ˆ๋‹ค.