티스토리 뷰
def solution(array):
count = {} #딕셔너리 생성
for i in array:
if i not in count:
#처음 나온 수
count[i] = 1
else:
# 빈도수 추가
count[i] += 1
#내림차순 저장
# items() 딕셔너리 키,값 쌍을 얻음
sorted_count = sorted(count.items(), key=lambda item : item[1], reverse = True)
#print("1",sorted_count)
#print("2",len(sorted_count))
#최빈값이 여러개일 때
if len(sorted_count) > 1 and sorted_count[0][1] == sorted_count[1][1]:
return -1
return sorted_count[0][0]
a = [2,3,4,2]
print(solution(a))
https://codechacha.com/ko/python-sorting-dict/#google_vignette
Python - dict 정렬 (Key, Value로 sorting)
dict(dictionary)를 Key 또는 Value를 기준으로 정렬하는 방법을 소개합니다. 다음과 같이 sorted()를 이용하여 dict를 정렬할 수 있습니다. 인자로 my_dict.items()를 전달하면 오름차순으로 정렬됩니다. 내림
codechacha.com
'Python' 카테고리의 다른 글
[PS][스택/큐] 주식 가격 (0) | 2024.07.03 |
---|---|
[PS] 햄버거 만들기 (lv.1) (0) | 2024.02.12 |
[PS] 같은 숫자는 싫어 (lv.1) (0) | 2024.02.07 |