[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])は、
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])は、
# 요소 별 nums 내의 개수가 nums 전체길이의 반을 초과할 때 반환
def more_than_half(nums):
for i in nums:
if nums.count(i) > len(nums)/2:
return i
def more_than_half(nums):
nums.sort() # 요소들을 순서대로 정렬
return nums[len(nums)//2] # 2로 나눈 몫을 인덱스로 갖는 값(정가운데 혹은 그의 하나 다음에 있는 값) 반환
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に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
Reference
この問題について([Codekata] Week2 - Day2), 我々は、より多くの情報をここで見つけました https://velog.io/@jungminnn/Codekata-Week2-Day2テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol