問題
B – 投票
回答
名前を辞書で管理し、ソートします。
N = int(input())
dict_names = dict()
for _ in range(N):
name = input()
if name not in dict_names:
dict_names[name] = 1
else:
dict_names[name] += 1
dict_names_sorted = sorted(dict_names.items(), key=lambda x:x[1], reverse=True)
print(dict_names_sorted[0][0])
defaultdict を使い、名前の取得を簡単にします。
key がない場合、エラーを起こさず指定した値をvalue にしてくれるので、記述が少し簡単になります。
import collections
N = int(input())
dict_names = collections.defaultdict(int)
for _ in range(N):
name = input()
dict_names[name] += 1
dict_names_sorted = sorted(dict_names.items(), key=lambda x:x[1], reverse=True)
print(dict_names_sorted[0][0])
Python には、Counter という数え上げを簡単に行えるオブジェクトが標準にあり、それを利用するとさらにコードが簡単になります。
import collections N = int(input()) names = [input() for _ in range(N)] dict_names = collections.Counter(names) print(dict_names.most_common(1)[0][0])