CSP 201312-1 出现次数最多的数

 一道很简单的题,但一开始做的很随便,题目也没看全:

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))

后来发现过是过了,但我没考虑多个相同值打印最小值的情况,非常离谱


于是有了第二版:

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)

这段代码基本上是考虑充分了,但是简单题写这么多行实在有点难受,于是继续改,有了第三版:

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)

用来setdefault直接抵消了前面的if判断,后面用列表表达式计算最小值看起来也舒适不少。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值