본문 바로가기
알고리즘 문제 풀이

백준 11652번 : 카드 (Python)

by 로널드 피셔 2022. 11. 1.

출처 : https://www.acmicpc.net/problem/11652

from collections import Counter

n = int(input())
nums = []

for i in range(n) :
    nums.append(int(input()))
    
nums.sort()
print(list(Counter(nums).most_common())[0][0])

파이썬 내장 라이브러리 collections의 Counter() 명령어는, 주어진 배열의 항목별 개수를 딕셔너리와 유사한 Counter라는 클래스로 변환해준다.

x = [1, 1, 1, 2, 2, 0, 0, 0]
y = Counter(x)
y

# 출력
Counter({1: 3, 2: 2, 0: 3})

또한 Counter.most_common() 메소드는 Counter 클래스를 항목별 개수가 많은 순서의 리스트로 변환한다.

y.most_common()

# 출력
[(1, 3), (0, 3), (2, 2)]

따라서 입력된 숫자들을 먼저 오름차순으로 정렬한 후, Counter와 most_common을 적용한 리스트의 0번째 인덱스에는 가장 가장 개수가 많은 정수와 그 정수의 개수가 튜플로 저장되어 있다.

 

* 이 문제는 백준 : 1302번 문제와 아주 유사하다.
https://www.acmicpc.net/problem/1302

댓글