T.I.L (알고리즘 문제의 문제 - 1)

2023. 3. 29. 20:51T.I.L (Today_I_Learned)

문제점


sorted_check = sorted(check.items(), reverse=True, key=lambda item: item[1])

 

문제 해결


  • check.items() 딕셔너리로 선언된 check의 key, value 값을 tuple형식으로 가져옵니다.
  • sorted(딕셔너리.items(), key=lambda item: item[1]) 이를 이용해서 key=를 item으로 세팅해주어서 정렬하도록 할 수 있습니다.
def solution(array):
    # answer = 0
    check = {}
    for ar in array:
        if ar not in check:
            check[ar] = 1
        else:
            check[ar] += 1

    sorted_check = sorted(check.items(), reverse=True, key=lambda item: item[1])
    # check.items() 딕셔너리로 선언된 check의 key, value 값을 tuple형식으로 가져옵니다.
    # sorted(딕셔너리.items(), key=lambda item: item[1]) 이를 이용해서 key=를 item으로 세팅해주어서 정렬하도록 할 수 있습니다.
    if len(sorted_check) > 1:
        if sorted_check[0][1] != sorted_check[1][1]:
            answer = sorted_check[0][0]
        else:
            answer = -1
    else:
        answer = sorted_check[0][0]

    return answer

 

'T.I.L (Today_I_Learned)' 카테고리의 다른 글

T.I.L (코딩 테스트 중 만난 pop 함수)  (5) 2023.03.31
T.I.L  (1) 2023.03.30
T.I.L (파이썬 턴제 게임 만들기)  (1) 2023.03.28
T.I.L (클래스 - 추가 정리)  (1) 2023.03.27
T.I.L (Python -클래스 class)  (0) 2023.03.24