본문 바로가기
[스파르타코딩클럽]데이터분석 과정/PYTHON

[Python 코드카타] 55 ~ 57번 (프로그래머스)

by doo_ 2024. 1. 23.

55번 카드뭉치

> 처음에 런타임 에러 문제가 있었는데

- cards1이 먼저 null값이 될 경우를 생각하지 못함 ( cards1 != []를 안 넣고 돌려서 오류)

def solution(cards1, cards2, goal):
    answer = ''
    while goal != []:
        if cards1 != [] and cards1[0] == goal[0]:
            cards1.pop(0)
            goal.pop(0)
        elif cards2 != [] and cards2[0] == goal[0]:
            cards2.pop(0)
            goal.pop(0)
        else : 
            answer = 'No'
            break
    if goal == [] :
        answer = 'Yes'
    return answer

> 깔끔한 답

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"

 

56번 과일 장수

> 시간 초과한 답..

def solution(k, m, score):
    answer = 0
    score.sort(reverse = True)
    while len(score) >= m:
        a = score[:m]
        for i in a:
            score.remove(i)
        answer += m*min(a)
    return answer

> 다시 푼 답

def solution(k, m, score):
    answer = 0
    score.sort(reverse = True)
    for i in range(0,len(score),m):
        a = score[i:i+m]
        if len(a) == m :
            answer += m*a[-1] # min(a)
    return answer

> 👏👏

def solution(k, m, score):
    return sum(sorted(score)[len(score)%m::m])*m
    # len(score)%m을 통해 해당 하지 않는 사과는 버리고 계산..

 

57번 모의고사 완전탐색

def solution(answers):
    answer = []
    # 1,2,3 학생의 찍는 패턴 구하기
    asw1 = [1,2,3,4,5]
    asw2 = [2,1,2,3,2,4,2,5]
    asw3 = [3,3,1,1,2,2,4,4,5,5]
    # 나머지를 활용, 각 해당 인덱스에 얼마나 맞추는지 score기록
    score = [0,0,0]
    for i in range(len(answers)):
        if asw1[i%len(asw1)] == answers[i]:
            score[0] += 1
        if asw2[i%len(asw2)] == answers[i]:
            score[1] += 1
        if asw3[i%len(asw3)] == answers[i]:
            score[2] += 1
    # 가장 많이 맞춘 idx를 구해 순서대로 넣기
    for idx, s in enumerate(score):
        if s == max(score):
            answer.append(idx+1)
    return answer

> 다른 답안인데 q가 0부터 4까지일텐데 의아함

def solution(answers):
    p = [[1, 2, 3, 4, 5],
         [2, 1, 2, 3, 2, 4, 2, 5],
         [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]]
    s = [0] * len(p)

    for q, a in enumerate(answers):
        for i, v in enumerate(p):
            if a == v[q % len(v)]:
                s[i] += 1
    return [i + 1 for i, v in enumerate(s) if v == max(s)]