阿里天池在线编程题目:“推荐朋友“ (基于python)

n个人的朋友名单,告诉你user是谁,请找出user最可能认识的人。(他和user有最多的共同好友且他不是user的朋友)

  • n <= 500
  • 好友关系是相互的。(b若出现在a的好友名单中,a一定出现在b的好友名单中)
  • 每个人的好友关系不超过 m 条,m <= 3000
  • 如果有两个人和user的共同好友数目一样,**编号更小**的那个认为是最可能认识的人。
  • 如果user和所有陌生人都没有共同好友,输出-1。

 

以下代码经测试通过:

class Solution:
    """
    @param friends: people's friends
    @param user: the user's id
    @return: the person who most likely to know
    """
    def recommendFriends(self, friends, user):
        # Write your code here 
        n=len(friends)
        num=len(friends[user])#目标的朋友数目
        friends_count=[0]*n #相同朋友计数
        for i in range(n):
            if(i!=user):#剔除自己
               for j in range(num):
                   if(friends[i].count(friends[user][j])>0):
                       friends_count[i]=friends_count[i]+1
                   if(friends[i].count(user)>0):#剔除现有朋友
                      friends_count[i]=0
        c=max(friends_count)
        if(c==0):
           return -1
        else:
          d=friends_count.index(c)
          return d

     

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值