+ 2
hiw to detect most frequency number in python array
ex- [1,1,2,6,6,6,6,9] most frequency number is 6 [1,1,1,8,6,7,7,7,9] most frequency number is 1 and 7
9 Réponses
+ 9
Damsara Welivita , Roshaan , Basil ,
> the use of statistics.mode(...) does not give a correct result if 2 numbers have the same number of occurrence. it only returns the first one.
> we can use statistics.multimode(...) instead.
see sample code in the file:
https://code.sololearn.com/cuqRZgC5EpeB/?ref=app
+ 2
To find the most frequently occurring number in a Python list, you can use the Counter class from the collections module.
+ 2
from collections import Counter
# Example arrays
arr1 = [1, 1, 2, 6, 6, 6, 6, 9]
arr2 = [1, 1, 1, 8, 6, 7, 7, 7, 9]
# Count the frequency of each number in the array
count1 = Counter(arr1)
count2 = Counter(arr2)
# Find the most common number(s) and their frequency
most_common1, freq1 = count1.most_common(1)[0]
most_common2 = count2.most_common(2)
freq2 = most_common2[0][1]
# Print the results
print(f"Array 1: {arr1}")
print(f"Most common number(s): {[num for num, count in most_common1]}")
print(f"Frequency: {freq1}")
print(f"\nArray 2: {arr2}")
print(f"Most common number(s): {[num for num, count in most_common2]}")
print(f"Frequency: {freq2}")
+ 1
Use a dict, it is very easy and simple:
array = [1,1,1,2,4,6,6,7,7,7,7,7]
s_2 = {}
for i in array:
s_2[i] = s_2.get(i, 0) + 1
print(max(s_2.keys(), key = lambda k: s_2[k]))
In the code below: there is an additional code for numbers from the highest number of repetitions to the lowest number of repetitions
https://code.sololearn.com/cY9Q7sEB4v49/?ref=app