5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

今更「1から10までの和の平均」とその実行速度

Posted at

はじめに

先日pythonにハローしたので初心に返って基礎演習みたいなことをしていた
今更ながら「1から10までの和の平均」なんてものをやってみました
その際の解法のご紹介

通常パターンのコード

# -*- coding: utf-8 -*-
def normal_average(start, end):
    # averageの計算時にfloatになるように0.0という初期化をしている
    sum = 0.0
    size = end - start + 1
    for i in range(start, end + 1):
        sum += i
    else:
        print "normal_average = %f"%(sum/size)

start = 1
end = 10
normal_average(start, end)

結果
normal_average = 5.500000

+1の部分がいけてない感あるけどまぁ良しとする
python初心者なのでお作法悪いところはご愛嬌

別パターンのコード

def another_average(start, end):
    print "another_average = %f"%((start + end)/2.0)

start = 1
end = 10
another_average(start, end)

結果
another_average = 5.500000

連続した整数の和の平均ってループなんて回さずともこれでいいんじゃないのとふと思ったので書いてみた
こんな解き方もアリかなと
これは数が多くなってくればそれだけ処理速度に差が出るはずだ

処理速度計測

数が多ければ多いほど差が出るはずなので、今回は1から1億までの和の平均を求めてみます

# -*- coding: utf-8 -*-
import time

def normal_average(start, end):
    sum = 0.0
    size = end - start + 1
    for i in range(start, end + 1):
        sum += i
    else:
        print "normal_average = %f"%(sum/size)

def another_average(start, end):
    print "another_average = %f"%((start + end)/2.0)


# メイン実行部
start = 1
end = 100000000

# 実行時間の計測
normal_start_time = time.time()
normal_average(start, end)
normal_end_time = time.time()
print "execute time is %f"%(normal_end_time - normal_start_time)
print

another_start_time = time.time()
another_average(start, end)
another_end_time = time.time()
print "execute time is %f"%(another_end_time - another_start_time)

結果
normal_average = 50000000.500000
execute time is 12.961456

another_average = 50000000.500000
execute time is 0.000006

(圧倒的じゃないか我軍は…!)
当たり前ですが処理速度が段違いですね

おわりに

そもそものロジックを変えれば圧倒的に早く結果を取れることもあるという話
もちろんこの解き方に問題がないわけではないですが、少なくとも「連続した整数の和の平均」を出すにはループ回すよりは早く求められますね
視点を変えて問題を解くのって大事という教訓でした

5
3
0

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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?