LoginSignup
3
3

More than 5 years have passed since last update.

プログラマの考えが・・身につく本より(Python):最頻値を求める

Last updated at Posted at 2016-05-13

前回の続き
今回は、配列の最頻値を求めるコード
C++での解答コードがすでに掲載されていますが、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;
    }
}

自分のpythonコード

test37.py
#!/usr/bin/env python
#coding:utf-8

import math

elem = [4,7,3,8,9,7,3,9,9,3,3,10]

###修正させていただいています
#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('配列=',elem, '\n' , '最頻値:',most,'|','回数:',high)


・・・(ターミナル実行)
>>> import test37
配列= [3, 3, 3, 3, 4, 7, 7, 8, 9, 9, 9, 10] 
 最頻値: 3 | 回数: 4
>>> 


前回の反省を生かして”リスト内包表記"や"ジェネレータ内包表記"を活用を考えてみましたが、どうしても current += 1 の部分でカウントをとらないといけなかったため上記のif文の繰り返しにしました。
実際に解答コードがありながらpythonに直すだけで時間かかってしまうので慣れないといけないなと感じます。

3
3
12

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3