본문 바로가기

Coding Test/Programmers

[프로그래머스/파이썬] 다리를 지나는 트럭

728x90

나의 풀이1

from collections import deque

def solution(bridge_length, weight, truck_weights):
    
    answer = 0
    truck_weights = deque(truck_weights)
    bridge = deque([0 for _ in range(bridge_length)])
    
    while truck_weights or sum(bridge):
        weight += bridge.popleft()
        
        if truck_weights and weight - truck_weights[0] >= 0:
            weight -= truck_weights[0]
            bridge.append(truck_weights.popleft())
            
        else:
            bridge.append(0)
            
        answer += 1
        
    return answer

 

나의 풀이 2

추가 예정

 

Class를 이용한 풀이

import collections

DUMMY_TRUCK = 0


class Bridge(object):

    def __init__(self, length, weight):
        self._max_length = length
        self._max_weight = weight
        self._queue = collections.deque()
        self._current_weight = 0

    def push(self, truck):
        next_weight = self._current_weight + truck
        if next_weight <= self._max_weight and len(self._queue) < self._max_length:
            self._queue.append(truck)
            self._current_weight = next_weight
            return True
        else:
            return False

    def pop(self):
        item = self._queue.popleft()
        self._current_weight -= item
        return item

    def __len__(self):
        return len(self._queue)

    def __repr__(self):
        return 'Bridge({}/{} : [{}])'.format(self._current_weight, self._max_weight, list(self._queue))


def solution(bridge_length, weight, truck_weights):
    bridge = Bridge(bridge_length, weight)
    trucks = collections.deque(w for w in truck_weights)

    for _ in range(bridge_length):
        bridge.push(DUMMY_TRUCK)

    count = 0
    while trucks:
        bridge.pop()

        if bridge.push(trucks[0]):
            trucks.popleft()
        else:
            bridge.push(DUMMY_TRUCK)

        count += 1

    while bridge:
        bridge.pop()
        count += 1

    return count

 

 

나와 비슷한 풀이

def solution(bridge_length, weight, truck_weights):
    q=[0]*bridge_length
    sec=0
    while q:
        sec+=1
        q.pop(0)
        if truck_weights:
            if sum(q)+truck_weights[0]<=weight:
                q.append(truck_weights.pop(0))
            else:
                q.append(0)
    return sec

 

 

마지막 더해주기

from collections import deque


def solution(bridge_length, weight, truck_weights):
    answer = 0
    tlist = deque()

    bsum = 0
    while len(truck_weights) != 0:
        answer += 1
        if (len(tlist) == bridge_length):
            bsum -= tlist.pop()
        temp = truck_weights[0]
        if (bsum + temp > weight):
            tlist.appendleft(0)
        else:
            bsum += temp
            tlist.appendleft(truck_weights.pop(0))

    return answer + bridge_length

 

반응형