Kee
Kee

Reputation: 163

How to find most repeat elements in lists?

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

Upvotes: 4

Views: 2159

Answers (2)

PythonProgrammi
PythonProgrammi

Reputation: 23443

from collections import Counter

a = ('2 3 40 1 5 4 3 3 9  9','9 30 3 9 3 1 4','19 30 13 4 9 3 1 4')

for x in a:
    x = x.split()
    b = Counter(x)
    z = max(b.values())
    for k in b.keys():
        if b[k] == z:
            print(k)

output:

3
9
3
4

If you want another output

from collections import Counter

a = ('2 3 40 1 5 4 3 3 9  9','9 30 3 9 3 1 4','19 30 13 4 9 3 1 4')

k = []
for x in a:
    x = x.split()
    b = Counter(x)
    z = max(b.values())
    k.append([f for f in b.keys() if b[f] == z])

print(k)

output

[['3'], ['9', '3'], ['4']]

Using a function

from collections import Counter

def maxmy(sequences):
    k = []
    for x in sequences:
        x = x.split()
        b = Counter(x)
        z = max(b.values())
        k.append([f for f in b.keys() if b[f] == z])
    return k

maxmy(('2 3 40 1 5 4 3 3 9  9','9 30 3 9 3 1 4','19 30 13 4 9 3 1 4'))

output

[['3'], ['9', '3'], ['4']]

Upvotes: 0

MSeifert
MSeifert

Reputation: 152597

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

Upvotes: 4

Related Questions