In this paper, the method of solving the problem of the majority of Python is described, and it is a more typical application. Share to everyone for your reference. Specific as follows:
Problem Description:
The most important element of the Multiset multiplicity is called the majority ... is a set of elements that can have duplicates, and the number of repetitions in this set is called its majority ...
if s = [1,2,2,2,3,5] weight is 2, its weight is 3
The instance code is as follows:
List_num = []list_num_count = 0dict_num ={} #从文件读入, the number of elements in the first behavior set of the file, after each behavior of an element 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# Find the number that has the most occurrences, find the Count Dict_sort_by_top = {}top_value = 0for valus in Dict_num.itervalues () : if valus> top_value: top_value = valus pass# Find the majority based on the number of re ... This is due to the fact that there may be multiple elements with the same number of 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_co UNT = values# output to a file, the first behavior from the number, the second behavior of the Write_line = '%s\n%s '% (the_pop_num, The_pop_num_count) Open ("Output.txt", ' W '). Write ( Write_line)
This assumes that there is a sibling directory file Input.txt content as follows:
811372372459937
The first row of 8 represents the number of elements, followed by an element for each row.
The test environment is Python2.7.6,
The results of the Python program operation for input.txt files are as follows:
The pop num is 37,and the appear num is 3
Simultaneous generation of the Output.txt file records the majority of 37 and its repetition number 3.
Hopefully this article will help you with Python programming.