Continuation of Last time This time, the code to find the mode of the array The answer code in C ++ has already been posted, but I rewrote it in python.
test.cpp
int mostFrequent;
int highestFrequency = 0;
int currentFrequency = 0;
for (int i = 0; i < ARRAY_SIZE; i++){
currentFrequency++;
if (i == ARRAY_SIZE - 1 || surveyData[i] != surveyData[i + 1]){
if (currentFrequency > highestFrequency){
highestFrequency = currentFrequency;
mostFrequent = surveyData[i];
}
currentFrequency = 0;
}
}
test37.py
#!/usr/bin/env python
#coding:utf-8
import math
elem = [4,7,3,8,9,7,3,9,9,3,3,10]
###I am fixing it
#count = {Elem.count(v):v for v in set(Elem)}
#high = max(count)
#most = count[high]
elem.sort()
most = 0
high = 0
current = 0
#for i,v in enumerate(Elem):
for i in range(len(elem)):
current += 1
if i == len(elem) - 1 or elem[i] != elem[i+1]:
if current > high:
high = current
most = elem[i]
current = 0
print('Array=',elem, '\n' , 'Mode:',most,'|','Number of times:',high)
・ ・ ・(Terminal execution)
>>> import test37
Array= [3, 3, 3, 3, 4, 7, 7, 8, 9, 9, 9, 10]
Mode: 3 |Number of times: 4
>>>
Taking advantage of the previous reflection, I thought about using "list comprehension" and "generator comprehension", but I had to count at the current + = 1 part, so I repeated the above if statement. Did. Even though there is an answer code, it takes time just to change it to python, so I feel that I have to get used to it.
Recommended Posts