코드카타 more_than_half

박대현·2021년 10월 31일
0

문제

숫자로 이루어진 배열인 nums를 인자로 전달합니다.

숫자중에서 과반수(majority, more than a half)가 넘은 숫자를 반환해주세요.

나의풀이

def more_than_half(nums):  
    return max(nums, key=nums.count)

in

정수형 숫자 배열

out

숫자중에서 과반수가 넘은 숫자

how

  1. 가장 많이 나오는 숫자를 찾고
  2. 그 숫자를 반환

다른풀이

def more_than_half(nums):
  nums.sort() # [1, 1, 1, 2, 2, 2, 2]
  return nums[len(nums)//2]
nums = [2,2,1,1,1,2,2]
print(more_than_half(nums))

가장 많은 숫자가 과반수인것을 이용하여 sort함수로 정렬 후 가운데 값을 찾는 방법

0개의 댓글