CSP 201312-1 Most frequently occurring number

 A very simple question, but I did it very casually at the beginning, and I didn't read the whole question:

n = int(input())
lst = list(map(int, input().split(" ")))
m = 0
temp = {}
for i in list(set(lst)):
    if lst.count(i) > m:
        m = lst.count(i)
        temp[i] = lst.count(i)
    else:
        continue
print(max(temp, key=temp.get))

Later, I found out that it was over, but I didn’t consider the case where multiple identical values ​​print the minimum value, which is very outrageous


So there is a second version:

n = int(input())
lst = list(map(int, input().split()))
count_dict = {}
for num in lst:
    if num not in count_dict:
        count_dict[num] = 1
    else:
        count_dict[num] += 1
max_count = max(count_dict.values())
min_num = float("inf")
for key, value in count_dict.items():
    if value == max_count and key < min_num:
        min_num = key
print(min_num)

This code is basically well thought out, but it is a bit uncomfortable to simply write so many lines, so I continued to modify it and got the third version:

n = int(input())
lst = list(map(int, input().split()))
count_dict = {}
for num in lst:
    count_dict.setdefault(num, 0)
    count_dict[num] += 1
max_count = max(count_dict.values())
min_num = min(key for key, value in count_dict.items() if value == max_count)
print(min_num)

Using setdefault directly offsets the previous if judgment, and it seems a lot more comfortable to use the list expression to calculate the minimum value later.

 

Guess you like

Origin blog.csdn.net/qq_53083744/article/details/129510765