python求众数问题实例

yipeiwu_com6年前Python基础

本文实例讲述了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 中re.sub,replace(),strip()的区别详解

对python 中re.sub,replace(),strip()的区别详解

1.strip(): str.strip([chars]);去除字符串前面和后面的所有设置的字符串,默认为空格 chars -- 移除字符串头尾指定的字符序列。 st = " he...

python实现通过flask和前端进行数据收发

python代码: # -*- coding: utf-8 -*- from flask import Flask,jsonify,render_template,request i...

python 日期操作类代码

完整代码 # -*- coding: utf-8 -*- '''获取当前日期前后N天或N月的日期''' from time import strftime, localtime...

使用python接入微信聊天机器人

本文实例为大家分享了python接入微信聊天机器人的具体代码,供大家参考,具体内容如下 1.安装库wxpy: pip install -U wxpy or pip instal...

浅谈Python的list中的选取范围

序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。 Python有6个序列的内置类型,但最常见的是列表...