Codewars 6 kyu Highest Rank Number in an Array
Task
Complete the method which returns the number which is most frequent in the given input array. If there is a tie for most frequent number, return the largest number among them.
Verbalization
- 各数字の出現回数を数える
- 最頻値を探す(回数が最大のもの)
Code
from collections import Counter
def highest_rank(arr):
counts = Counter(arr)
max_count = max(counts.values())
candidates = []
for num, cnt in counts.items():
if cnt == max_count:
candidates.append(num)
return max(candidates)
Reference
出現回数を数えるのは、collections.Counterが便利(from collections import Counter)
辞書の値として値が保存される
https://docs.python.org/ja/3.13/library/collections.html#collections.Counter