Algorithms/프로그래머스

[프로그래머스] Lv1. 모의고사 - 완전탐색

devran 2023. 10. 26. 22:10
반응형

1️⃣ 모의고사

문제

https://school.programmers.co.kr/learn/courses/30/lessons/42840?language=python3

💡 아이디어

말그대로 완전탐색을 해준다!

인덱스 순서에 유의하며 문제를 풀었다.

📝 풀이

나머지를 활용해서 인덱스를 구하였고, dict를 사용하여 append 해주었다.

다소 비효율적이고 매우 풀어썼음

def solution(answers):
    answer = []
    a = [1, 2, 3, 4, 5]
    b = [2, 1, 2, 3, 2, 4, 2, 5]
    c = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
    
    aa = 0
    bb = 0
    cc = 0
 
    for i in range(len(answers)):
        if a[(i + 1) % len(a) - 1] == answers[i]:
            aa += 1
        if b[(i + 1) % len(b) - 1] == answers[i]:
            bb += 1
        if c[(i + 1) % len(c) - 1] == answers[i]:
            cc += 1
    
    dict = {'1' : aa, '2': bb, '3':cc}
    
    max = 0
    for items in dict:
        if dict[items] >= max:
            if dict != 0:
                max = dict[items]
            
    for items in dict:
        if dict[items] == max:
            if items == '1':
                answer.append(1)
            if items == '2':
                answer.append(2)
            if items == '3':
                answer.append(3)
            
    return answer

구글링 하다 찾은 다른 사람들 간단한 풀이

def solution(answers):
    supojas = [[1,2,3,4,5],[2,1,2,3,2,4,2,5], [3,3,1,1,2,2,4,4,5,5]]
    res = []
    for person in supojas:
        k, count = 0, 0
        length = len(person)
        for ans in answers:
            if ans == person[k]:
                count+=1
            k+=1
            k%=length
        res.append(count)
        
    maxvalue = max(res)
    answer= []
    for i in range(3):
        if res[i] == maxvalue:
            answer.append(i+1)
    return answer

👩🏻‍💻 느낀점

이중배열을 쓰면 코드가 훨씬 간단해진다

반응형