欧几里德距离递归函数

时间:2016-02-10 17:17:35

标签: lisp

我要写一个递归函数来找到给定2个列表的欧几里德距离,该列表总是被假定为大小相等。 2列表代表矢量。

以下是我的代码,但是我错过了最后一步,即在最后一次递归调用之后将整个结果平方根。我可以不引入任何变量吗?

import collections
def groupByAnagram2(word_list):
    dic = collections.defaultdict(list)
    for x in word_list:
       sort = ''.join(sorted(x))
       dic[sort].append(x)

    for words in dic.values():
        for word in words:
            print word

Formula to euclidean distance I am implementing

编辑:我尝试了建议页面中的答案,并在测试时遇到错误。 enter image description here

它说(defun distance (l1 l2) (if (null l1) 0 (+ (expt (- (first l1) (first l2)) 2) (distance (rest l1) (rest l2)))))

The variable SQ-EUCLIDEAN-DISTANCE is unbound.

1 个答案:

答案 0 :(得分:-2)

func distance(l1, l2):  
   if l1 == null || l2 == null  
      return 0  
   else  
      return sqrt((l1.first - l2.first) * (l1.first - l2.first) + distance(rest(l1), rest(l2)))