[Codekata] Week2 - Day2

8343 ワード

質問する


数値配列numsをパラメータとして渡します.
数字のうち半数を超える(多数、半を超える)数字を返してください.
たとえば、
nums = [3,2,3]
return 3

nums = [2,2,1,1,1,2,2]
return 2

家庭

nums配列の長さは、2より大きくなければならない.

に答える


#1


最も簡単で、多くの人が選択する方法です.ただし、データ量が大きくなると運転時間が長くなります.
# 요소 별 nums 내의 개수가 nums 전체길이의 반을 초과할 때 반환
def more_than_half(nums):
    for i in nums:
      if nums.count(i) > len(nums)/2:
        return i
ここから,これらはリストに必ず半数を超える数の数が存在すると仮定した解である.

#2

def more_than_half(nums):
  nums.sort()                  # 요소들을 순서대로 정렬
  return nums[len(nums)//2]    # 2로 나눈 몫을 인덱스로 갖는 값(정가운데 혹은 그의 하나 다음에 있는 값) 반환

#3

def more_than_half(nums):
  m = {}
  for n in nums:
    m[n] = m.get(n, 0) + 1
    if m[n] > len(nums) // 2:
      return n

dictionary.get(a, b)


方法(dictionary[a])は、
  • dictionaryのaに対応するキー値を返す.
  • 辞書[a]との違いは、
    dictionaryにaというキーがない場合は、エラーは発生せずにbというデフォルト値を返します.
  • 例:
  • >>> a_dict = {'hi': 1, 'bye': 2}
    >>> a_dict.get('hi', 5)
    1
    >>> a_dict.get('oh', 5)
    5
    >>> a_dict
    {'hi': 1, 'bye': 2}    # get으로 dictionary에 추가가 되진 않음

    #4

    def more_than_half(nums):
      count_dict = {}
      result = 0
      max_count = 0
    
      # dictionary 안에 요소 별 개수 저장
      for num in nums:
        if num not in count_dict:
          count_dict[num] = 1
        else:
          count_dict[num] += 1
          
        # 요소 별 개수를 계속 비교하며 저장
        if count_dict[num] > max_count:
          result = num
          max_count = count_dict[num]
    
        return result