[SWEA] 1204번 - 최빈수 구하기

김멉덥·2023년 7월 1일
0

알고리즘 공부

목록 보기
15/171
post-thumbnail

문제

D2 - 1204. [S/W 문제해결 기본] 1일차 - 최빈수 구하기


코드 구현

정답 코드

from collections import Counter

T = int(input())
for t in range(0, T):
    N = int(input())    # 테스트케이스 번호
    score_arr = list(map(int, input().split()))     # 점수를 저장할 배열

    mode = (Counter(score_arr)).most_common()   # 최빈값 구하기 -> 내람차순 정리
    max_mode = mode[0][0]   # 최종 최빈값

    print("#%d %d" %(N, max_mode))

풀이

▶️ 파이썬 최빈값 구하기

  • Counter는 사전(dict) 클래스의 하위 클래스로 리스트나 튜플에서 각 데이터가 등장한 횟수를 보여줌
    from collections import Counter
    
    colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
    cnt = Counter(colors)
    cnt
    
    >>> Counter({'blue': 3, 'red': 2, 'green': 1})
  • Counter 클래스의 most_common() 메쏘드는 등장한 횟수를 내림차순으로 정리
    from collections import Counter
    
    numbers = [1, 2, 3, 3, 4, 4, 4, 5, 5]
    cnt = Counter(numbers)
    cnt.most_common()
    
    >>> [(4, 3), (3, 2), (5, 2), (1, 1), (2, 1)]
  • 최빈값 얻기
    mode = cnt.most_common(1)
    mode
    >>> [(4, 3)]
    
    **mode[0][0]**
    >>> 4

profile
데굴데굴 뚝딱뚝딱 개발기록

0개의 댓글