首页 > 编程 > Python > 正文

python求众数问题实例

2020-02-23 05:53:00
字体:
来源:转载
供稿:网友

本文实例讲述了python求众数问题的方法,是一个比较典型的应用。分享给大家供大家参考。具体如下:

问题描述:

多重集中重数最大的元素称为众数...就是一个可以有重复元素的集合,在这个集合中重复的次数最多的那个数就叫它的众数...
如S = [1,2,2,2,3,5] 重数是2,其重数为3

实例代码如下:

list_num = []list_num_count = 0dict_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 = 0for valus in dict_num.itervalues():  if valus> top_value:    top_value = valus  pass#根据重数找到众数...这是因为考虑到可能有多个元素有相同多的重数the_pop_num = 0the_pop_num_count = 0for 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内容如下:

811372372459937

第一行的8代表元素个数,其后每一行有一个元素。

测试环境为Python2.7.6,

Python程序针对input.txt文件操作的运行结果如下:

the pop num is 37,and the appear num is 3

同时生成output.txt文件记录了众数37及其重复次数3。

希望本文所述对大家的Python程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表