Drkcore

18 01 2010 Haskell Python Tweet

pythonでユークリッド距離

haskellのK-meansのソース読んでたら

dist a b = sqrt . sum $ zipWith (\x y-> (x-y) ^ 2) a b

ってのがあって、pythonでzipWithってあったかなーと思って検索したら、自分のwikiが引っかかった。★付けたいところ。

これをつかうと

from math import *
zipWith = lambda f, xs, ys : [f(x, y) for x,y in zip(xs, ys)]
def dist(xs, ys): return sqrt(sum(zipWith(lambda x, y: (x-y)**2, xs, ys)))

となって、任意の次元にも対応出来る

>>> dist([1,2,3,4],[2,2,2,2])
2.4494897427831779

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021