알고리즘/완전탐색

[프로그래머스] 모의고사 - 파이썬(python)

아뵹젼 2022. 9. 6.

 

나의 풀이

def solution(answers):
    answer = []
    count = len(answers)
    one = ([1,2,3,4,5] * (count//5 + 1))[:count]
    two = ([2,1,2,3,2,4,2,5] * (count//8 + 1))[:count]
    three = ([3, 3, 1, 1, 2, 2, 4, 4, 5, 5] * (count//10 + 1))[:count]
    
    score = [0,0,0]
    
    print(one, two, three)
    
    for i in range(count) :
        if answers[i] == one[i] : 
            score[0] += 1
        if answers[i] == two[i] : 
            score[1] += 1
        if answers[i] == three[i] : 
            score[2] += 1
            
    max_score = max(score)
    for i,j in enumerate(score) :
        if j == max_score : answer.append(i+1)
        
    return answer

1번, 2번, 3번의 답안을 one, two, three 에 만들었다.

그리고, 정답지를 for문으로 돌면서 각 답과 1,2,3번의 답을 비교하면서 score 리스트의 0,1,2번 인덱스에 점수를 부여하였다.

마지막으로, score 리스트의 최댓값에 해당하는 인덱스+1 번을 answer 리스트에 담아 리턴해주었다.

 

 

 

다른 풀이

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

나는 미리 1,2,3번의 답안을 초기화했었는데, 이 분은 pattern을 사용하여 공간을 줄일 수 있었다.

 

 

from itertools import cycle

def solution(answers):
    giveups = [
        cycle([1,2,3,4,5]),
        cycle([2,1,2,3,2,4,2,5]),
        cycle([3,3,1,1,2,2,4,4,5,5]),
    ]
    scores = [0, 0, 0]
    for num in answers:
        for i in range(3):
            if next(giveups[i]) == num:
                scores[i] += 1
    highest = max(scores)

    return [i + 1 for i, v in enumerate(scores) if v == highest]

itertools 모듈의 cycle 을 사용한 깔끔한 코드이다.

 

 

 

 

cycle

순환하고 싶은 리스트를 cycle 함수의 인자로 넣어주면 무한 순환이 가능한 iterator(반복자)를 리턴한다.

cycle('ABCD') --> A B C D A B C D ...

 

 

 

next, iter 

출처 : https://dojang.io/mod/page/view.php?id=2408

 

 

 next는 이터레이터에서 값을 차례대로 꺼낸다.

it = iter(range(3))
>>> next(it)
0
>>> next(it)
1
>>> next(it)
2
>>> next(it)
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    next(it)
StopIteration

 

iter는 반복을 끝낼 값을 지정하면 특정 값이 나올 때 반복을 끝낸다.

이 경우에는 반복 가능한 객체 대신 호출 가능한 객체(callable)를 넣어준다.

  • iter(호출가능한객체, 반복을끝낼값)

ex) random.randint(0, 5)와 같이 0부터 5까지 무작위로 숫자를 생성할 때 2가 나오면 반복을 끝내도록 만들 수 있다. 

>>> import random
>>> it = iter(lambda : random.randint(0, 5), 2)
>>> next(it)
0
>>> next(it)
3
>>> next(it)
1
>>> next(it)
Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    next(it)
StopIteration

 

next(it)로 숫자를 계속 만들다가 2가 나오면 StopIteration이 발생한다.

아래처럼 for 반복문에 넣어서 사용할 수도 있다.

>>> import random
>>> for i in iter(lambda : random.randint(0, 5), 2):
...     print(i, end=' ')
...
3 1 4 0 5 3 3 5 0 4 1 

댓글