jjinyeok 성장일지

프로그래머스 Study 1주차 본문

[Coding Study]

프로그래머스 Study 1주차

jjinyeok 2023. 4. 30. 23:08

폰켓몬

def solution(nums):
    nums_no_dupl = set(nums) # 중복 제외
    return min(len(nums) // 2, len(nums_no_dupl))

 

완주하지 못한 선수

def solution(participant, completion):
    # 정렬
    participant.sort()
    completion.sort()
    
    for i in range(len(completion)):
        if participant[i] != completion[i]:
            return participant[i] # 정렬했으므로 겹치지 않은 참가자가 완주하지 못함
    return participant[-1] # 끝까지 반복문을 돈 경우 마지막 참가자가 완주하지 못함

 

전화번호 목록

def solution(phone_book):
    # 접두어 리스트
    prefixs = {}
    for phone_num in phone_book:
        for i in range(1, len(phone_num) + 1):
            if phone_num[:i] not in prefixs:
                prefixs[phone_num[:i]] = 1 # 한번만 나온 접두어 (본인을 포함하기 때문에 정답이 될 수 없는 경우)
            else:
                prefixs[phone_num[:i]] = 2 # 두번 이상 나온 접두어
    
    for phone_num in phone_book:
        if prefixs[phone_num] == 2:
            return False
    return True

 

의상

def solution(clothes):
    # 옷 조합 해시 생성
    cloth_dic = {}
    for cloth, cloth_type in clothes:
        if cloth_type not in cloth_dic:
            cloth_dic[cloth_type] = 1
        else:
            cloth_dic[cloth_type] += 1
    # 계산
    answer = 1
    for key, value in cloth_dic.items():
        answer *= (value + 1)
    return answer - 1

 

베스트앨범

from collections import Counter

def solution(genres, plays):
    
    n = len(genres)
    answer = []
    
    genre_count = {} # key: genre, value: sum(play_count)
    for i in range(n):
        if genres[i] in genre_count:
            genre_count[genres[i]] += plays[i]
        else:
            genre_count[genres[i]] = plays[i]
    sorted_genres = sorted(genre_count, key = lambda x: - genre_count[x])
    
    dic = {} # key: genre, value: list([play_count, index])
    for i in range(n):
        if genres[i] in dic:
            dic[genres[i]].append([plays[i], i])
        else:
            dic[genres[i]] = [[plays[i], i]]
    
    for genre in sorted_genres:
        sorted_plays = sorted(dic[genre], key = lambda x: (-x[0], x[1]))
        for i in range(min(2, len(sorted_plays))):
            answer.append(sorted_plays[i][1])
    
    return answer

 

같은 숫자는 싫어

def solution(arr):
    preval = arr[0]
    answer = [preval]
    for i in range(1, len(arr)):
        if arr[i] != preval:
            answer.append(arr[i])
            preval = arr[i]
    return answer

 

기능개발

def solution(progresses, speeds):
    
    answer = []
    idx = 0
    while progresses:
        count = 0
        for i in range(len(progresses)):
            progresses[i] += speeds[i] # 모든 개발 하루 진행
        while True:
            if idx < len(progresses) and progresses[idx] >= 100: # 통과
                idx += 1
                count += 1
            else:
                break
        if count != 0:
            answer.append(count)
        if idx == len(progresses):
            break
    return answer

 

올바른 괄호

def solution(s):
    
    stack = []
    for i in s:
        if len(stack) > 0 and stack[-1] == '(' and i == ')':
            stack.pop()
        else:
            stack.append(i)
    
    return True if stack == [] else False

 

프로세스

from collections import deque
def solution(priorities, location):
    q = deque()
    for idx in range(len(priorities)):
        q.append([priorities[idx], idx]) # [우선순위, 순번]
        
    results = []
    while q:
        priority, idx = q.popleft()
        if len(q) == 0:
            results.append(idx)
        elif priority >= max(q, key = lambda x: x[0])[0]:
            results.append(idx)
        else:
            q.append([priority, idx])
    
    for i in range(len(results)):
        if location == results[i]:
            return i + 1

 

다리를 지나는 트럭

from collections import deque

def solution(bridge_length, weight, truck_weights):
    
    count = 0
    truck_weights = deque(truck_weights)
    bridge = deque()
    
    # 더 이상 대기 트럭이 없을 때까지 매초 시간이 흐름
    while truck_weights or bridge:
        # 1. bridge의 트럭은 시간이 감
        for truck_in_bridge in bridge:
            truck_in_bridge[1] += 1
        
        # 2. bridge의 트럭이 bridge_length만큼 있었다면 popleft()
        while True:
            if bridge and bridge[0][1] == bridge_length:
                bridge.popleft()
            else:
                break
        
        # 3. weight보다 (현재 트럭 무게) + (bridge의 트럭들 무게)가 작거나 같다면 bridge.append([현재 트럭 무게, 0])
        bridge_weights = 0
        for truck_in_bridge in bridge:
            bridge_weights += truck_in_bridge[0]
        if truck_weights and weight >= bridge_weights + truck_weights[0]:
            bridge.append([truck_weights[0], 0])
            truck_weights.popleft()
                
        count += 1
                
    return count

 

주식가격

def solution(prices):
    answer = []
    for i in range(len(prices)):
        count = 0
        check = True
        for j in range(i + 1, len(prices)):
            if prices[i] <= prices[j]:
                count += 1
            else:
                answer.append(count + 1)
                check = False
                break
        if check:
            answer.append(count)
    return answer

 

K번째수

def solution(array, commands):
    answer = []
    for command in commands:
        i, j, k = command
        answer.append(sorted(array[i - 1: j])[k - 1])
    return answer

 

최소직사각형

def solution(sizes):
    for size in sizes:
        size.sort()
    max_w, max_h = 0, 0
    for w, h in sizes:
        if w > max_w:
            max_w = w
        if h > max_h:
            max_h = h
    return max_w * max_h

 

모의고사

def solution(answers):
    
    answer = []
    a = [1, 2, 3, 4, 5] * 2000
    b = [2, 1, 2, 3, 2, 4, 2, 5] * 1250
    c = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5] * 1000
    
    scores = [0, 0, 0]
    for i in range(len(answers)):
        if answers[i] == a[i]:
            scores[0] += 1
        if answers[i] == b[i]:
            scores[1] += 1
        if answers[i] == c[i]:
            scores[2] += 1
    
    for i in range(3):
        if scores[i] == max(scores):
            answer.append(i + 1)
    answer.sort()
    
    return answer

 

못 푼 문제: 체육복 (난 왜 Greedy에 약할까...)

'[Coding Study]' 카테고리의 다른 글

프로그래머스 Study 6주차  (0) 2023.07.16
프로그래머스 Study 5주차  (0) 2023.07.09
프로그래머스 + BOJ Study 4주차  (0) 2023.06.29
프로그래머스 Study 3주차  (0) 2023.06.23
프로그래머스 Study 2주차  (0) 2023.05.07
Comments