[프로그래머스] Lv1. 모의고사

24275 단어 pspythonps

문제

접근 방법

  • 각 학생들이 찍는 패턴을 리스트로 선언
  • 반복문을 돌며 각 학생들의 점수 확인
  • 최고 점수의 학생 찾기

이전에 C++로 풀었던 내용

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

bool comp(pair<int, int> a, pair<int, int> b){
    return a.second > b.second;
}

vector<int> solution(vector<int> answers) {
    vector<int> answer;
    vector<pair<int, int>> temp;
    vector<int> arr1 = {1, 2, 3, 4, 5};
    vector<int> arr2 = {2, 1, 2, 3, 2, 4, 2, 5};
    vector<int> arr3 = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
    
    int score1 = 0;
    int score2 = 0;
    int score3 = 0;
    
    for(int i = 0; i < answers.size(); i++){
        if(answers[i] == arr1[i%5]) score1++;
        if(answers[i] == arr2[i%8]) score2++;
        if(answers[i] == arr3[i%10]) score3++;
    }
    
    temp.push_back(make_pair(1, score1));
    temp.push_back(make_pair(2, score2));
    temp.push_back(make_pair(3, score3));
    
    sort(temp.begin(), temp.end(), comp);

    answer.push_back(temp[0].first);
    if(temp[0].second == temp[1].second) answer.push_back(temp[1].first);
    if(temp[0].second == temp[2].second) answer.push_back(temp[2].first);

    return answer;
}
}

나의 풀이

def solution(answers):
    answer = []
    
    student1 = [1, 2, 3, 4, 5]
    student2 = [2, 1, 2, 3, 2, 4, 2, 5]
    student3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
    
    score = {1 : 0, 2 : 0,  3 : 0}
    
    for i, a in enumerate(answers):
        if a == student1[i % len(student1)]:
            score[1] += 1
        if a == student2[i % len(student2)]:
            score[2] += 1
        if a == student3[i % len(student3)]:
            score[3] += 1
    
    max_score = 0
    
    for v in score.values():
        if v > max_score:
            max_score = v
            
    for i, v in score.items():
        if v == max_score:
            answer.append(i)
    
    return answer

생각해보니 굳이 최댓값을 구할 때 반복문을 사용하지 않아도 된다.

def solution(answers):
    answer = []
    
    student1 = [1, 2, 3, 4, 5]
    student2 = [2, 1, 2, 3, 2, 4, 2, 5]
    student3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
    
    score = {1 : 0, 2 : 0,  3 : 0}
    
    for i, a in enumerate(answers):
        if a == student1[i % len(student1)]:
            score[1] += 1
        if a == student2[i % len(student2)]:
            score[2] += 1
        if a == student3[i % len(student3)]:
            score[3] += 1
    
    max_score = max(score.values())
            
    for i, v in score.items():
        if v == max_score:
            answer.append(i)
    
    return answer

좋은 웹페이지 즐겨찾기