[프로그래머스] 1단계_모의고사 (python)

juyeon·2022년 6월 15일
0

코딩테스트(python)

목록 보기
9/22

프로그래머스

1단계_모의고사

나의 풀이

  1. 실패
def solution(answers):
    answer = []
    solution = [0, 0, 0]
    one = [1, 2, 3, 4, 5]
    two = [2, 1, 2, 3, 2, 4, 2, 5]
    three = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
    
    for i in range(len(answers)):
        if one[i % 5] == answers[i]:
            solution[0] += 1
        if two[i % 8] == answers[i]:
            solution[1] += 1
        if three[i % 10] == answers[i]:
            solution[2] += 1
            
    answer.append(solution.index(max(solution)) - 1 )
    
    return answer

: 자꾸 결과값이 -1이 나온다..뭐가 문제지?
-> 문제점 찾음!!

answer.append(solution.index(max(solution)) - 1 )

: 이렇게 하면, max 값이 여러개 일 때 문제가 발생!

리스트 매소드 중에서 index()는 리스트 중에서 특정한 원소가 몇 번째에 처음으로 등장했는지를 알려준다. 그런데 두 번 이상 원소가 중복되어 존재하는 경우에는 맨 처음 등장한 순간의 인덱스를 출력해준다는 점을 기억하자.

  1. 성공
def solution(answers):
    answer = []
    solution = [0, 0, 0]
    one = [1, 2, 3, 4, 5]
    two = [2, 1, 2, 3, 2, 4, 2, 5]
    three = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
    
    for i in range(len(answers)):
        if one[i % 5] == answers[i]:
            solution[0] += 1
        if two[i % 8] == answers[i]:
            solution[1] += 1
        if three[i % 10] == answers[i]:
            solution[2] += 1
            
    if solution[0] == max(solution):
        answer.append(1)
    if solution[1] == max(solution):
        answer.append(2)
    if solution[2] == max(solution):
        answer.append(3)
    #공동 1등 가능성 때문에 elif를 안 씀
    
    return answer

: 마지막 answer.appen 부분을 수정 했더니... 통과가 됐다..?

다른 사람 풀이(프로그래머스)

def solution(answers):
    pattern1 = [1,2,3,4,5]
    pattern2 = [2,1,2,3,2,4,2,5]
    pattern3 = [3,3,1,1,2,2,4,4,5,5]
    score = [0, 0, 0]
    result = []

    for idx, answer in enumerate(answers):
        if answer == pattern1[idx%len(pattern1)]:
            score[0] += 1
        if answer == pattern2[idx%len(pattern2)]:
            score[1] += 1
        if answer == pattern3[idx%len(pattern3)]:
            score[2] += 1

    for idx, s in enumerate(score):
        if s == max(score):
            result.append(idx+1)

    return result

: enumerate 함수!!
: https://velog.io/@juyeonma9/조각-문법-for-python

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)]

: 변수명이 너무 짧고 반복문이 중첩되어서..결국 댓글을 봤다

"첫번째 반복문에서 enumerate를 썻으니 q=0 일때; a는 anwers의 첫번째 값입니다 그걸 데리고 가서 두번째 반복문에서 i=0 일때; v는 p의 첫번째값 즉, [1,2,3,4,5]가 됩니다.
if 절에서 a의 값은 answers의 첫번째입니다. v[q% len(v)]는 v중에서 q%len(v) 번째를 나타냅니다. 여기선, v[0나누기5의나머지] 니까 v[0] 입니다. [1,2,3,4,5] 에서 0번째 놈이고, '나머지'를 쓰는 이유는 한번 고민해보시길 바랍니다.
다시 answers의 첫번째 랑 v리스트의 첫번째랑 같냐? 라고 물어서 같으면 해당 위치에 +1 해주는 겁니다."

profile
내 인생의 주연

0개의 댓글