문제풀이/일일연습문제

[Brute Force]99클럽 코테 스터디 15일차 TIL + 프로그래머스/1/42840. 모의고사

Mo_bi!e 2024. 8. 5. 18:44

문제 설명

수포자는 수학을 포기한 사람의 준말입니다. 수포자 삼인방은 모의고사에 수학 문제를 전부 찍으려 합니다. 수포자는 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하는 값을 오름차순 정렬해주세요.
입출력 예
answers return
[1,2,3,4,5] [1]
[1,3,2,4,2] [1,2,3]
입출력 예 설명

입출력 예 #1

  • 수포자 1은 모든 문제를 맞혔습니다.
  • 수포자 2는 모든 문제를 틀렸습니다.
  • 수포자 3은 모든 문제를 틀렸습니다.

따라서 가장 문제를 많이 맞힌 사람은 수포자 1입니다.

입출력 예 #2

  • 모든 사람이 2문제씩을 맞췄습니다.

 

 

<내코드>

def solution(answers):
    first, second, third = [], [], []

    first_pattern = [1, 2, 3, 4, 5]
    second_pattern = [2, 1, 2, 3, 2, 4, 2, 5]
    third_pattern = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]

    i = 0
    f = 0
    s = 0
    t = 0
    while len(answers) > i:
        first.append(first_pattern[f])
        if len(first_pattern) -1 > f:
            f += 1
        else:
            f = 0

        second.append(second_pattern[s])
        if len(second_pattern) -1 > s:
            s += 1
        else:
            s = 0

        third.append(third_pattern[t])
        if len(third_pattern) -1 > t:
            t += 1
        else:
            t = 0
        i += 1

    correct_f = 0
    correct_s = 0
    correct_t = 0
    for i in range(len(answers) ):
        if first[i] == answers[i]:
            correct_f += 1
        if second[i] == answers[i]:
            correct_s += 1
        if third[i] == answers[i]:
            correct_t += 1

    answer = []
    max_value = max(correct_f,correct_s,correct_t)
    if max_value == correct_f:
        answer.append(1)
    if max_value == correct_s:
        answer.append(2)
    if max_value == correct_t:
        answer.append(3)
    return answer

1. 헤맨부분

- 처음에는 문제 이해를 못함

=> 1,2,3 번째 문제를 찍은 횟수가 조건으로 주어지는지 알았음. 하지만 문제에 주어진 패턴을 찾아서 반복적으로 정답을 직접 입력하게 해야했음

 

- len() 관련 헷갈리게 내가 시도함

=> len 은 딱 그 길이만큼만 리턴을 함, 

range() 와 있을 때 더 헷갈리는데, range(stop) 이면 stop - 1 까지 반복을 하는것

 

<모범사례>

- 라이브러리 사용한경우

* itertools 모듈의 사용

cycle 는 iterable한 요소들이 순환하며 반환하는 내용을 생성하는 것이다.

 

* zip 은 각각 인자의 이터러블한 값 하나씩을 튜플로 묶어줌

def solution(answers):
    from itertools import cycle

    # 수포자 패턴
    first_pattern = cycle([1, 2, 3, 4, 5])
    second_pattern = cycle([2, 1, 2, 3, 2, 4, 2, 5])
    third_pattern = cycle([3, 3, 1, 1, 2, 2, 4, 4, 5, 5])

    # 맞춘 개수
    correct_f = sum(1 for a, p in zip(answers, first_pattern) if a == p)
    correct_s = sum(1 for a, p in zip(answers, second_pattern) if a == p)
    correct_t = sum(1 for a, p in zip(answers, third_pattern) if a == p)

    # 최대값 구하기
    max_value = max(correct_f, correct_s, correct_t)

    # 결과 반환
    result = []
    if correct_f == max_value:
        result.append(1)
    if correct_s == max_value:
        result.append(2)
    if correct_t == max_value:
        result.append(3)
    
    return result

 

 

 

- 라이브러리 사용하지 않은경우

* patten 리스트에다가 나머지 연산을 이용해서 그 부분을 반복해서 추출 해내는 방식도 가능함

def solution(answers):
    # 수포자 패턴
    first_pattern = [1, 2, 3, 4, 5]
    second_pattern = [2, 1, 2, 3, 2, 4, 2, 5]
    third_pattern = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]

    # 맞춘 개수 초기화
    correct_f = correct_s = correct_t = 0

    # 답안 비교
    for i in range(len(answers)):
        if answers[i] == first_pattern[i % len(first_pattern)]:
            correct_f += 1
        if answers[i] == second_pattern[i % len(second_pattern)]:
            correct_s += 1
        if answers[i] == third_pattern[i % len(third_pattern)]:
            correct_t += 1

    # 최대값 구하기
    max_value = max(correct_f, correct_s, correct_t)

    # 결과 반환
    result = []
    if correct_f == max_value:
        result.append(1)
    if correct_s == max_value:
        result.append(2)
    if correct_t == max_value:
        result.append(3)
    
    return result

 

 

<보충학습>

1. 연습문제 풀기

- itertools 의 cycle 연습하기

- zip() 연습하기

- pattern[i % len(pattern)] 연습하기

 

 

import itertools

# 주어진 리스트 colors = ["red", "green", "blue"]가 있습니다. 이 리스트의 색상들을 무한히 반복하여 출력하는 코드를 작성하세요. 총 10개의 색상을 출력하면 됩니다.
colors = ["red", "green", "blue"]

colors_cycle = itertools.cycle(colors)

for i in range(10):
    print(next(colors_cycle))

#2 각 사람의 이름과 나이를 함께 출력하는 코드를 작성하세요.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

for n, a in zip(names, ages):
    print(n, a)

# 3 주어진 패턴 pattern = [1, 2, 3, 4, 5]이 있습니다. 이 패턴을 사용하여 길이가 12인 새로운 리스트를 생성하세요.
pattern = [1, 2, 3, 4, 5]

result = []
for i in range(12):
    result.append(pattern[i % len(pattern)])
print(result)

# 4 각 letters 요소에 대해 numbers 요소를 순환시켜 다음과 같은 출력 형식을 만드세요:
letters = ["a", "b", "c"]
numbers = [1, 2, 3, 4, 5, 6]

num_cycle = itertools.cycle(numbers)

for letter in letters:
    for _ in range(len(numbers)):
        print(letter, next(num_cycle))
print("***")
#5 각 letters 요소와 numbers 요소를 순환하여 zip을 사용하여 다음과 같이 출력하세요:
letters = ["a", "b", "c"]
numbers = [1, 2, 3, 4, 5, 6]

letter_cycle = itertools.cycle(letters)
numbers_cycle = itertools.cycle(numbers)

for l, n in zip(letter_cycle,numbers):
    print(l , n)

# 6 각 사람의 이름, 나이, 도시를 함께 출력하는 코드를 작성하세요.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["New York", "Los Angeles", "Chicago"]

for n, a, c in zip(names,ages,cities):
    print(n , a , c)

 

 

- 매번 헷갈리는 리스트 컴프리헨션 연습하기

# 1 . 주어진 리스트 numbers = [1, 2, 3, 4, 5]의 각 요소를 제곱한 값을 가지는 리스트를 만드세요.
numbers = [1, 2, 3, 4, 5]

list_num = [x **2 for x in numbers]
print(list_num)

# 2. 주어진 리스트 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]에서 짝수만 필터링하여 새로운 리스트를 만드세요.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filter_num = [x for x in numbers if x % 2 == 0]
print(filter_num)

# 3. 주어진 리스트 words = ["apple", "banana", "cherry"]의 각 문자열의 길이를 가지는 리스트를 만드세요.
words = ["apple", "banana", "cherry"]
len_list = [len(word) for word in words]
print(len_list)

# 4. 주어진 중첩 리스트 matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]를 하나의 평탄한 리스트로 만드세요.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix_list = [num for row in matrix for num in row]
print(matrix_list)

# 5. 문제: 주어진 리스트 words = ["hello", "world"]의 각 문자열을 대문자로 변환하여 새로운 리스트를 만드세요.
words = ["hello", "world"]
words_list = [word.upper() for word in words]
print(words_list)

# 6. 두 리스트 list1 = [1, 2, 3]과 list2 = [4, 5, 6]이 주어졌을 때, 각 요소를 곱한 값을 가지는 새로운 리스트를 만드세요.
list1 = [1, 2, 3]
list2 = [4, 5, 6]

new_list = [a * b for a, b in zip(list1, list2)]
print(new_list)