코딩테스트/programmers
[level 0]최빈값 구하기
EunGyeongKim
2022. 10. 11. 15:08
더 많은 코드 (https://github.com/EunGyeongKim/TIL)
GitHub - EunGyeongKim/TIL: Today I Learne
Today I Learne. Contribute to EunGyeongKim/TIL development by creating an account on GitHub.
github.com
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
1. 문제 설명
최빈값은 주어진 값 중에서 가장 자주 나오는 값을 의미합니다. 정수 배열 array
가 매개변수로 주어질 때, 최빈값을 return 하도록 solution 함수를 완성해보세요. 최빈값이 여러 개면 -1을 return 합니다.
2. 제한사항
- 0 <
array
의 길이 < 100 - 1000 <
array
의 원소 < 1000
3. 입출력 예
array | result |
---|---|
[1, 2, 3, 3, 3, 4] | 3 |
[1, 1, 2, 2] | -1 |
[1] | 1 |
4. 코드
from collections import Counter
def solution(array):
count_key = []
count_val = []
# array 갯수 세기
for key, val in Counter(array).items():
# count한 data를 list에 각각 넣어주기
count_key.append(key)
count_val.append(val)
# 최빈값 찾기
max_val = max(count_val)
# 최빈값이 1개일때
if count_val.count(max(count_val)) == 1:
return count_key[count_val.index(max(count_val))]
# 최빈값이 2개 이상일때
else :
return -1