Lists count total amount and higher repeat

Asked

Viewed 836 times

-1

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

3 answers

2

Yes, it is possible to use this command by importing the package statistics

follows the solution:

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

2

Use the 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 the 8 is the most common, appearing 3 times.

0

You can use the function max specifying vetor.count in the parameter key to find 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 the Repl.it

There is the risk of there being more than one number repeating more times, for example, and in this case will return what appears first in the list.

  • Although it does not make a difference in this simple example, I would like to comment that this code is "quadratic", that is, it searches in the list every single element of the list, scanning the same O² times. If the list is long it could take quite a while.

  • I believe you meant O(n 2). The idea of the answer is to have an alternative to not having to import an external package. In an external package it is more difficult to know the complexity unless you have documentation or look at the code. Perhaps an O(n log n) alternative is possible by writing the algorithm itself.

  • In this case, the package is not external. Both the module collections how much statistics of the other answers, are an integral part of the official python.

  • I expressed myself badly. External package meant to import a package, either from lib that comes with Python or from a third party. With native commands you can better understand what it will do, with a package you need to go deeper to know the complexity. For example, in this collections.Counter as I know the complexity that is running to create the dictionary with each item and its count?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.