本文實例講述了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程序設計有所幫助。
新聞熱點
疑難解答