Codecata ⎜ 과반수 이상인 숫자 출력하기
과반수 이상인 숫자 출력하기
문제
숫자로 이루어진 배열인 nums를 인자로 전달합니다.
숫자중에서 과반수(majority, more than a half)가 넘은 숫자를 반환해주세요.
예를 들어, nums = [3,2,3] return 3
nums = [2,2,1,1,1,2,2] return 2
- 가정 nums 배열의 길이는 무조건 2개 이상
내가 한 풀이
접근방법
- 과반수 값을 구한다.
- 주어진 리스트를 딕셔너리로 만든다.
- 딕셔너리 값 중 과반수보다 크거나 같은 키를 리턴한다.
def more_than_half(nums):
    count = len(nums)
    majority = (count // 2) + 1
    my_dic = {}
    for num in nums:
        if num not in my_dic:
            my_dic[num] = 1
        else:
            my_dic[num] += 1
    # print(majority)
    # print(my_dic)
    for key, value in my_dic.items():
        if value >= majority:
            return key
print(more_than_half([3, 2, 3, 1, 3, 3, 3, 2, 3]))
위코드 풀이
Boolean값을 변수선언으로 로직이 시작된다. 아직까지 Boolean 값을 변수로 주는 것에 대해 익숙하지 않다.
def more_than_half(nums):
    count = len(nums)
    majority = (count // 2) + 1
    my_dic = {}
    for num in nums:
        if num not in my_dic:
            my_dic[num] = 1
        else:
            my_dic[num] += 1
    # print(majority)
    # print(my_dic)
    for key, value in my_dic.items():
        if value >= majority:
            return key
print(more_than_half([3, 2, 3]))
 
      
     
      
댓글남기기