Lists count total quantity and highest repetition [closed]

-1

Hello, I would like to know how I can count the number of items in a vector, and also show the number that appears the most. Example: Given the vector [1,2,3,4,5,6,7,8,8,8] There are 10 elements 8 (number with most repetition)

    
asked by anonymous 13.09.2018 / 19:54

3 answers

2
___ erkimt ___ Lists count total quantity and highest repetition [closed] ______ qstntxt ___

Hello, I would like to know how I can count the number of items in a vector, and also show the number that appears the most. Example: Given the vector [1,2,3,4,5,6,7,8,8,8] There are 10 elements 8 (number with most repetition)

    
______ ___ azszpr329421

Yes, you can use this command matter statistics

The solution follows:

import statistics
a =  [1,2,3,4,5,6,7,8,8,8]
len(a)
#10
statistics.mode(a)
#8
    
______ azszpr329423 ___

Use %code% :

import statistics
a =  [1,2,3,4,5,6,7,8,8,8]
len(a)
#10
statistics.mode(a)
#8

This means that 8 is the most common, appearing 3 times.

    
______ azszpr329462 ___

You can use the max function by specifying %code% in parameter %code% to search the fashion of the list.

%pre%

Running on Repl.it

There is a risk that there will be more than one number repeating more times, for example, and in that case it will return what appears first in the list.

    
___
13.09.2018 / 21:07
2

Use collections.Counter :

>>> import collections
>>> vetor = [1,2,3,4,5,6,7,8,8,8]

>>> c = collections.Counter(vetor)
>>> print(c)
Counter({8: 3, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1})

>>> print(c.most_common(1))
[(8, 3)] 

This means that 8 is the most common, appearing 3 times.

    
13.09.2018 / 21:09
0

You can use the max function by specifying vetor.count in parameter key to search the fashion of the list.

vetor = [1,2,3,4,5,6,7,8,8,8]

print ("tamanho: {}, moda: {}".format(len(vetor), max(vetor, key = vetor.count)))

Running on Repl.it

There is a risk that there will be more than one number repeating more times, for example, and in that case it will return what appears first in the list.

    
13.09.2018 / 22:59