博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【LintCode 简单】445. 余弦相似度
阅读量:4088 次
发布时间:2019-05-25

本文共 1116 字,大约阅读时间需要 3 分钟。

1.问题描述:

Cosine similarity is a measure of similarity between two vectors of an inner product space that measures the cosine of the angle between them. The cosine of 0° is 1, and it is less than 1 for any other angle.

See wiki: 

Here is the formula:

cosine-similarity

Given two vectors A and B with the same size, calculate the cosine similarity.

Return 2.0000 if cosine similarity is invalid (for example A = [0] and B = [0]).

2.样例:

给出 A = [1, 2, 3]B = [2, 3 ,4].

返回 0.9926.

给出 A = [0]B = [0].

返回 2.0000

3.代码:

class Solution:    """    @param: A: An integer array    @param: B: An integer array    @return: Cosine similarity    """    def cosineSimilarity(self, A, B):        # write your code here        length=len(A)        molecule=0        donominator1=0        donominator2=0        fg=False        for i in range(length):            if (A[i] or B[i]) and fg==False:                fg=True            molecule+=A[i]*B[i]            donominator1+=A[i]*A[i]            donominator2+=B[i]*B[i]        if fg:            ans=molecule/((donominator1**0.5)*(donominator2**0.5))            return ans        else:            return 2

转载地址:http://nouii.baihongyu.com/

你可能感兴趣的文章
flutter踩坑高德地图amap_base
查看>>
flutter极光推送
查看>>
jvm崩溃并输出 hs_err_pidxxxx.log文件异常原因
查看>>
HXAPIGate(中文名:浩心API网关)
查看>>
Nginx搭建TCP反向代理服务
查看>>
netty整合shiro,报There is no session with id [xxxxxx]问题定位及解决
查看>>
Ignite配置
查看>>
Ignite计算网格第一部分
查看>>
将表单序列化之后变成的json格式的数据无法通过Ajax发送到后台的解决
查看>>
使用JAVA代码实现字符串的简单拼接
查看>>
java中的模版方法
查看>>
实现从oss(阿里云)服务器以附件形式下载文件(含批量下载)
查看>>
JSP页面以GET方式传参服务器报400
查看>>
自定义百度地图全局搜索结果的信息窗口
查看>>
SSM框架Jsp页面POST提交的中文数据保存到数据库变成乱码问题的分析
查看>>
j2ee编程实现将数据变成json格式的高效转换工具fastJson
查看>>
如何自己成功搭建一个SSM框架的WEB项目
查看>>
webservice知识一、SOAP风格的webservice——通过JDK的API发布一个webservice服务和创建一个webservice客户端用于访问该服务
查看>>
JavaEE开发之Spring中的多线程编程以及任务定时器详解(有源码)
查看>>
JS实现2,8,10,16进制的相互转换
查看>>