本文實例講述了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程序設計有所幫助。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
