SW Expert Academy-1204-Python

cosmos·2023년 4월 24일
0
post-thumbnail

코드

from typing import List

def top_cnt_num(scores: List[int]) -> int:
    dict = {}
    
    for num in scores:
        if num not in dict:
            dict[num] = 1
        else:
            dict[num] += 1
    
    return sorted(dict.items(), key=lambda x: (x[-1], x[0]), reverse=True)[0][0]

T = int(input())

for test_case in range(1, T + 1):
    test_case_num = int(input())
    scores = list(map(int, input().split()))
    print(f'#{test_case_num} {top_cnt_num(scores)}')

결과

ChatGPT Code

T = int(input())

for test_case in range(1, T+1):
    input()  # 테스트 케이스 번호는 이미 주어졌으므로 입력 받지 않음
    scores = list(map(int, input().split()))
    
    counts = [0] * 101  # 점수가 0점 ~ 100점이므로 101개의 원소를 가지는 리스트 생성
    
    # 각 점수마다 등장 횟수를 카운트
    for score in scores:
        counts[score] += 1
    
    mode = 0  # 최빈수를 저장할 변수
    max_count = 0  # 현재까지 등장한 최대 횟수
    
    # 100점부터 0점까지 역순으로 최빈수를 찾음
    for i in range(100, -1, -1):
        if counts[i] >= max_count:
            mode = i
            max_count = counts[i]
    
    print(f"#{test_case} {mode}")

ChatGPT 문제풀이

위 코드는 각 테스트 케이스마다 다음과 같은 작업을 수행합니다.
학생들의 점수를 입력받습니다.
각 점수마다 등장 횟수를 세어 리스트에 저장합니다.
100점부터 0점까지 역순으로 최빈수를 찾습니다.
최빈수를 출력합니다.
위 코드에서 주의해야 할 점은 counts 리스트를 생성할 때, 인덱스 i에 해당하는 점수의 등장 횟수를 저장하는 것이 아니라, counts[i]에 해당하는 인덱스가 i인 점수의 등장 횟수를 저장한다는 것입니다. 이를 통해, counts[i]가 i 점수의 등장 횟수가 되도록 리스트를 만들 수 있습니다.

문제출처 & 깃허브

SW Expert Academy
Github

0개의 댓글