python求眾數(shù)問題實例
本文實例講述了python求眾數(shù)問題的方法,是一個比較典型的應用。分享給大家供大家參考。具體如下:
問題描述:
多重集中重數(shù)最大的元素稱為眾數(shù)...就是一個可以有重復元素的集合,在這個集合中重復的次數(shù)最多的那個數(shù)就叫它的眾數(shù)...
如S = [1,2,2,2,3,5] 重數(shù)是2,其重數(shù)為3
實例代碼如下:
list_num = [] list_num_count = 0 dict_num ={} #從文件讀入,文件第一行為集合中元素的個數(shù),以后每一行為一個元素 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 #找到出現(xiàn)次數(shù)最多的那個數(shù),找到重數(shù) dict_sort_by_top = {} top_value = 0 for valus in dict_num.itervalues(): if valus> top_value: top_value = valus pass #根據(jù)重數(shù)找到眾數(shù)...這是因為考慮到可能有多個元素有相同多的重數(shù) 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 #輸出到文件,第一行為從數(shù),第二行為重數(shù) write_line = '%s\n%s' %(the_pop_num, the_pop_num_count) open("output.txt",'w').write(write_line)
這里假設有同級目錄文件input.txt內(nèi)容如下:
8 11 37 2 37 2 45 99 37
第一行的8代表元素個數(shù),其后每一行有一個元素。
測試環(huán)境為Python2.7.6,
Python程序針對input.txt文件操作的運行結(jié)果如下:
the pop num is 37,and the appear num is 3
同時生成output.txt文件記錄了眾數(shù)37及其重復次數(shù)3。
希望本文所述對大家的Python程序設計有所幫助。
相關文章
Python3實現(xiàn)監(jiān)控新型冠狀病毒肺炎疫情的示例代碼
這篇文章主要介紹了Python3實現(xiàn)監(jiān)控新型冠狀病毒肺炎疫情的示例代碼,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02