import math from itertools import imap v1 = [30, 20, 20, 10, 0] v2 = [40, 0, 30, 20, 10] dot_product = sum(imap(lambda a, b: a * b, v1, v2)) module_one = math.sqrt(sum(imap(lambda a, b: a * b, v1, v1))) module_two = math.sqrt(sum(imap(lambda a, b: a * b, v2, v2))) similarity = -1 try: = float(dot_product) / (module_one * module_two) except Exception,e: print "ZeroDivisonError,check it" print similarity
具體解釋參考 http://cyxinda.blog.163.com/blog/static/3659618620136306469889/spa