python求众数问题实例

WBOY
Release: 2016-06-16 08:41:42
Original
3362 people have browsed it

本文实例讲述了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)

Copy after login

这里假设有同级目录文件input.txt内容如下:

8
11
37
2
37
2
45
99
37
Copy after login

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

测试环境为Python2.7.6,

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

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

Copy after login

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

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template