Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find most repeat elements in lists?

Tags:

python

counter

def print_most_numbers_occurrences(numbers_str):
    number_list = numbers_str.split() 
    for i in number_list:
        i=max(number_list,key=number_list.count)
    print(i)


def test_print_most_numbers_occurrences():
     print_most_numbers_occurrences('2 3 40 1 5 4 3 3 9  9')
     print_most_numbers_occurrences('9 30 3 9 3 1 4')
     print_most_numbers_occurrences('19 30 13 4 9 3 1 4')

def main():
    test_print_most_numbers_occurrences()


main()

output:

3
9
4

I want to get all most repeating numbers for '9 30 3 9 3 1 4': 9 and 3 appear twice, so both occurrences should be reported not only 9

output looks like this:

3
9
3
4
like image 856
Kee Avatar asked Oct 29 '25 17:10

Kee


1 Answers

First: You don't need the for-loop when you use max. It already does that for you.

Second: If you want to have more than one value then max isn't really a good choice. For these kind of counting operations you should use collections.Counter (it also avoids counting the number of occurrences multiple times).

from collections import Counter

def print_most_numbers_occurrences(numbers_str):
    number_list = numbers_str.split() 
    # count the occurrences
    cnts = Counter(number_list)
    # Get the maximum count
    maximum_cnt = max(cnts.values())
    # print all values that have the "maximum" count
    print(*[val for val, cnt in cnts.items() if cnt == maximum_cnt])

And the test with your inputs prints:

3
9 3
4

If you prefer simple loops over comprehensions (or you use python-2.x without the print function) you could also use:

def print_most_numbers_occurrences(numbers_str):
    number_list = numbers_str.split() 
    cnts = Counter(number_list)
    maximum_cnt = max(cnts.values())
    for value, cnt in cnts.items():
        if cnt == maximum_cnt:
            print(value)

which gives:

3
9
3
4
like image 144
MSeifert Avatar answered Oct 31 '25 06:10

MSeifert