Find the value of the list that occurs most often
The list is given. Determine the most common value in it.
The program below searches for only one value. If two values occur at the same frequency in the list, only one of them will be defined.
from random import random a = [int(random()*5) for i in range(15)] print(a) a_set = set(a) most_common = None qty_most_common = 0 for item in a_set: qty = a.count(item) if qty > qty_most_common: qty_most_common = qty most_common = item print(most_common)
Example of execution:
[1, 2, 2, 2, 1, 3, 2, 0, 2, 1, 3, 2, 4, 0, 4] 2
from random import random # Filling the list with random numbers from 0 to 4. # The quantity of items in the list is 15. # The list generator is used for filling. a = [int(random()*5) for i in range(15)] print(a) # The list is converted to a set. # In it all elements are unique. a_set = set(a) most_common = None # most common value qty_most_common = 0 # its quantity # the cycle bypasses the elements (items) of the set for item in a_set: # the qty variable is assigned the number # of occurrences of the item in the list qty = a.count(item) # If the qty is greater than the maximum, if qty > qty_most_common: qty_most_common = qty # then overwrite the maximum, most_common = item # remember the value of the element # output value print(most_common)