[wecode/codekata]Day 7

Jimin_Note·2022년 6월 14일
0

⌨️wecode/code_kata

목록 보기
7/13
post-thumbnail

📍문제

숫자로 이루어진 배열인 nums를 인자로 전달합니다.
숫자중에서 과반수(majority, more than a half)가 넘은 숫자를 반환해주세요.

numsreturn
[3,2,3]3
[2,2,1,1,1,2,2]2

<가정>
nums 배열의 길이는 무조건 2 이상입니다.

📍내 코드

def more_than_half(nums):
   a={}
   for i in nums:
    if i not in a: #딕셔너리 a 안에 i가 없으면
      a[i] = 1     #해당 value = 1
    else:       
      a[i]=a[i]+1  #없으면 value+1
   
   return max(a, key=a.get)  #value가 가장 큰 key값 찾기

📍코드 수정.1

def more_than_half(nums):
    
  dict1 = {}
  #b = []
  for i in set(nums):
    dict1.setdefault(i, nums.count(i))
  
  return max(dict1, key=dict1.get)

📍코드 수정.2

def more_than_half(nums):
 b = []
  for i in set(nums):
     if nums.count(i) > len(nums)/2:
      b.append(i)
  return b[0] 
profile
Hello. I'm jimin:)

0개의 댓글