-
프로그래머스 고득점 kit(유형정리) - 모의고사Algorithm/Brute Force 2023. 1. 27. 09:49728x90
코딩테스트 연습 - 모의고사 | 프로그래머스 스쿨 (programmers.co.kr)
문제 설명
수포자는 수학을 포기한 사람의 준말입니다. 수포자 삼인방은 모의고사에 수학 문제를 전부 찍으려 합니다. 수포자는 1번 문제부터 마지막 문제까지 다음과 같이 찍습니다.
1번 수포자가 찍는 방식: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
2번 수포자가 찍는 방식: 2, 1, 2, 3, 2, 4, 2, 5, 2, 1, 2, 3, 2, 4, 2, 5, ...
3번 수포자가 찍는 방식: 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, ...1번 문제부터 마지막 문제까지의 정답이 순서대로 들은 배열 answers가 주어졌을 때, 가장 많은 문제를 맞힌 사람이 누구인지 배열에 담아 return 하도록 solution 함수를 작성해주세요.
제한 조건- 시험은 최대 10,000 문제로 구성되어있습니다.
- 문제의 정답은 1, 2, 3, 4, 5중 하나입니다.
- 가장 높은 점수를 받은 사람이 여럿일 경우, return하는 값을 오름차순 정렬해주세요.
[1,2,3,4,5] [1] [1,3,2,4,2] [1,2,3] 입출력 예 #1
- 수포자 1은 모든 문제를 맞혔습니다.
- 수포자 2는 모든 문제를 틀렸습니다.
- 수포자 3은 모든 문제를 틀렸습니다.
따라서 가장 문제를 많이 맞힌 사람은 수포자 1입니다.
입출력 예 #2
- 모든 사람이 2문제씩을 맞췄습니다.
※ 알고리즘
1. 수포자 1, 2, 3이 정답을 찍을 방식을 한 주기로 끊어서 list에 담는다.
2. 맞춘 갯수를 담을 count 변수를 3개 선언한다.
3. for문 안에서 answers 리스트와의 비교를 통해 수포자 1, 2, 3이 정답을 맞추면 count를 +1 해준다.
4. count 변수 3개를 리스트 형식으로 뽑아내야 하므로 list화 시켜준다.
5. count_list의 길이만큼 for문을 돌려서 count_list[i]와 count_list의 max 값(가장 문제를 많이 맞춘 사람)이 같을 때, answer 리스트에 index+1의 형식으로 append 시켜준다.
6. return 값을 오름차순 정렬하기 위해 sorting 시켜준다.
def solution(answers): answer = [] first = [1,2,3,4,5] second = [2,1,2,3,2,4,2,5] third = [3,3,1,1,2,2,4,4,5,5] count1 = 0 count2 = 0 count3 = 0 for i in range(len(answers)): if answers[i] == first[i%len(first)]: count1 += 1 if answers[i] == second[i%len(second)]: count2 += 1 if answers[i] == third[i%len(third)]: count3 += 1 count_list = [count1, count2, count3] for i in range(len(count_list)): if count_list[i] == max(count_list): answer.append(i+1) answer.sort() return answer
이 문제를 위의 알고리즘대로 풀었을 때, 실행은 되었지만 효율성 테스트에서 런타임에러가 발생했다. 오류가 어디서 날까를 고민해 보니, 한 주기가 8개나 10개 일 경우 len(answers) 길이 만큼만 돌도록 하니 index 에러가 발생하는 것이라는 생각에 주기만큼으로 i를 나누어 조금 더 효율적으로 구현해보았다. 그랬더니 성공!!!
728x90'Algorithm > Brute Force' 카테고리의 다른 글
프로그래머스 고득점 kit(유형정리) - 모음사전 (0) 2023.02.02 프로그래머스 고득점 kit(유형정리) - 카펫 (0) 2023.02.01 프로그래머스 고득점 kit(유형정리) - 피로도 (1) 2023.02.01 프로그래머스 고득점 kit(유형정리) - 소수찾기 (0) 2023.01.31 프로그래머스 고득점 kit(유형정리) - 최소직사각형 (0) 2023.01.27