AT's Blog

プログラミング、回路設計、ギター、音楽、読書とか

Python3でリスト同士の共分散を計算させてみた

Overview

コードと実行結果

# -*- coding: utf-8 -*-

class Analystic:
    def __init__(self):
        pass
    
    def average(self, ls):
        return(sum(ls)/len(ls))

    def dispersion(self, ls):
        ave = self.average(ls)

        return(sum([(x-ave)**2 for x in ls]) / len(ls))

    def stddev(self, ls):
        return(self.dispersion(ls)**0.5)

    def covariance(self, ls1, ls2):
        ave1 = self.average(ls1)
        ave2 = self.average(ls2)

        return(self.average(list(map(lambda x, y: (x-ave1)*(y-ave2), ls1, ls2))))
    
def main():
    ls = [4,5,6]
    ls1 = [1,4,7]
    ls2 = [4,5,6]
               
    a = Analystic()
    print(a.average(ls))
    print(a.dispersion(ls))
    print(a.stddev(ls))
    print(a.covariance(ls1,ls2))
               
if __name__=='__main__':
    main()
5.0
0.6666666666666666
0.816496580927726
2.0

感想

  • map()便利だなぁ(小並感)
  • iteratorの仕組みというか概念がいまいち理解できてません。