DevYoon

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋‹ค๋ฆฌ๋ฅผ ์ง€๋‚˜๋Š” ํŠธ๋Ÿญ (Python) ๋ณธ๋ฌธ

PS/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋‹ค๋ฆฌ๋ฅผ ์ง€๋‚˜๋Š” ํŠธ๋Ÿญ (Python)

gimewn 2022. 4. 26. 15:46

link ๐Ÿ”— https://programmers.co.kr/learn/courses/30/lessons/42583

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋‹ค๋ฆฌ๋ฅผ ์ง€๋‚˜๋Š” ํŠธ๋Ÿญ

ํŠธ๋Ÿญ ์—ฌ๋Ÿฌ ๋Œ€๊ฐ€ ๊ฐ•์„ ๊ฐ€๋กœ์ง€๋ฅด๋Š” ์ผ์ฐจ์„  ๋‹ค๋ฆฌ๋ฅผ ์ •ํ•ด์ง„ ์ˆœ์œผ๋กœ ๊ฑด๋„ˆ๋ ค ํ•ฉ๋‹ˆ๋‹ค. ๋ชจ๋“  ํŠธ๋Ÿญ์ด ๋‹ค๋ฆฌ๋ฅผ ๊ฑด๋„ˆ๋ ค๋ฉด ์ตœ์†Œ ๋ช‡ ์ดˆ๊ฐ€ ๊ฑธ๋ฆฌ๋Š”์ง€ ์•Œ์•„๋‚ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๋‹ค๋ฆฌ์—๋Š” ํŠธ๋Ÿญ์ด ์ตœ๋Œ€ bridge_length๋Œ€ ์˜ฌ๋ผ๊ฐˆ

programmers.co.kr

 

์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚ฌ๋˜ ์ฝ”๋“œ

def solution(bridge_length, weight, truck_weights):
    answer = 1
    bridge = [0]*bridge_length
    bridge[0] = truck_weights.pop(0)
    while sum(bridge)!=0:
        for idx in range(bridge_length-1, -1, -1):
            if idx == bridge_length-1 and bridge[idx] != 0:
                bridge[idx] = 0
            elif bridge[idx] != 0:
                bridge[idx+1] = bridge[idx]
                bridge[idx] = 0
        if len(truck_weights) > 0:
            if sum(bridge)+truck_weights[0] <= weight and bridge[0] == 0:
                bridge[0] = truck_weights.pop(0)
        answer += 1

    return answer

 

์ˆ˜์ • ์ฝ”๋“œ

def solution(bridge_length, weight, truck_weights):
    answer = 0
    bridge = [0]*bridge_length
    sum_bridge = 0
    while len(bridge):
        answer += 1
        sum_bridge -= bridge[0]
        bridge.pop(0)
        if len(truck_weights):
            if sum_bridge+truck_weights[0] <= weight:
                bridge.append(truck_weights.pop(0))
                sum_bridge += bridge[-1]
            else:
                bridge.append(0)

    return answer

 

โœ๏ธ ๋ฉ”๋ชจ

  • ํ…Œ์ŠคํŠธ์ผ€์ด์Šค 5๋ฒˆ์—์„œ ๊ณ„์† ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚ฌ๋‹ค.
  • ์—ฌ๋Ÿฌ ๋ฒˆ์˜ ์‹œ๋„ ๋์— sum(bridge)๋กœ ํ•ฉ์„ ๊ตฌํ•ด์ค€ ๊ฒŒ ๋ฌธ์ œ์ธ ๊ฒƒ ๊ฐ™๋‹ค๊ณ  ๋Š๊ผˆ๋‹ค.
  • sum์„ ์“ฐ์ง€ ์•Š๊ณ  sum_bridge๋ผ๋Š” ๋ณ€์ˆ˜๋ฅผ ๋”ฐ๋กœ ์‚ฌ์šฉํ•ด์„œ appendํ•  ๋• sum_bridge์— ๊ทธ ๊ฐ’์„ ๋”ํ•ด์ฃผ๊ณ , pop ํ•  ๋• ๊ทธ ๊ฐ’์„ ๋นผ์ฃผ๋Š” ์‹์œผ๋กœ ์ˆ˜์ •ํ–ˆ๋‹ค.
  • ํ…Œ์ŠคํŠธ์ผ€์ด์Šค 5 ์‹œ๊ฐ„ ์ดˆ๊ณผ ํ•ด๊ฒฐ!