python求众数问题实例
作者:shichen2014 时间:2022-02-06 22:25:40
本文实例讲述了python求众数问题的方法,是一个比较典型的应用。分享给大家供大家参考。具体如下:
问题描述:
多重集中重数最大的元素称为众数...就是一个可以有重复元素的集合,在这个集合中重复的次数最多的那个数就叫它的众数...
如S = [1,2,2,2,3,5] 重数是2,其重数为3
实例代码如下:
list_num = []
list_num_count = 0
dict_num ={}
#从文件读入,文件第一行为集合中元素的个数,以后每一行为一个元素
list_num_count = int(open('input.txt','r').readline())
for line_num, line in enumerate(open("input.txt",'r')):
if line_num > 0:
list_num += line.split()
#将读到的元素加入的字典中
for item in list_num:
if dict_num.has_key(item):
dict_num[item] += 1
else:
dict_num.setdefault(item,1)
pass
#找到出现次数最多的那个数,找到重数
dict_sort_by_top = {}
top_value = 0
for valus in dict_num.itervalues():
if valus> top_value:
top_value = valus
pass
#根据重数找到众数...这是因为考虑到可能有多个元素有相同多的重数
the_pop_num = 0
the_pop_num_count = 0
for keys,values in dict_num.iteritems():
if values == top_value:
print 'the pop num is %s,and the appear num is %s' % (keys,values)
the_pop_num = keys
the_pop_num_count = values
#输出到文件,第一行为从数,第二行为重数
write_line = '%s\n%s' %(the_pop_num, the_pop_num_count)
open("output.txt",'w').write(write_line)
这里假设有同级目录文件input.txt内容如下:
8
11
37
2
37
2
45
99
37
第一行的8代表元素个数,其后每一行有一个元素。
测试环境为Python2.7.6,
Python程序针对input.txt文件操作的运行结果如下:
the pop num is 37,and the appear num is 3
同时生成output.txt文件记录了众数37及其重复次数3。
希望本文所述对大家的Python程序设计有所帮助。
标签:python
0
投稿
猜你喜欢
微信小程序按钮点击动画效果的实现
2023-08-26 03:22:21
javaScript通用数据类型校验函数
2009-07-06 12:49:00
Python用正则表达式实现爬取古诗文网站信息
2021-08-30 07:12:51
python字符串连接方法分析
2021-12-24 16:27:10
条件CSS的使用[译]
2009-03-12 12:23:00
W3C优质网页小贴士(一)
2008-04-06 16:35:00
ASP初学者常犯的几个错误
2007-09-07 10:19:00
Tag与Tagging
2009-10-15 12:59:00
详解ASP中断开记录集的使用方法
2008-02-13 08:35:00
python数据拟合之scipy.optimize.curve_fit解读
2021-05-27 01:48:49
Web前端应用十种常用技术
2010-09-01 20:46:00
微信小程序图片左右摆动效果详解
2023-08-09 13:34:31
javascript弹出窗口总结
2009-08-21 12:40:00
asp怎么实现中文字符串按声母检索
2010-05-16 21:19:00
python批量翻译excel表格中的英文
2022-11-16 08:09:07
DropDownList绑定选择数据报错提示异常解决方案
2023-07-18 04:36:13
浅谈python print(xx, flush = True) 全网最清晰的解释
2022-01-28 21:45:48
tf.concat中axis的含义与使用详解
2021-05-21 12:38:00
Google的用户体验设计原则
2009-01-12 18:31:00
利用ASP实现事务处理的方法
2010-05-11 16:53:00