首页 > 解决方案 > 使用python找到具有递归函数的路径

问题描述

我正在尝试创建此功能,该功能将帮助我查看朋友列表和朋友或朋友列表,以便了解我应该查找多少步骤或朋友列表才能在我的列表中找到连续用户early_adopters.

到目前为止我所拥有的:

early_adopter = ['2347507100',
                  '1353186810',
                  '897960223662424064']

#distances between early adopters
def get_distance(usr1, usr2):
  follower_list=[]
  path = 0
  for user in tweepy.Cursor(api.followers, user_id = usr1).items(4):
      follower_list.append(user.id)
  if usr2 in follower_list:
    path =+ 1
    return path
  elif usr2 not in follower_list: 
    #repeat the same step above but this time with the user of the follower list, and this will count another step in the path, I want to repeat this process 3 times.
  else:
    return 0


dist = [get_distance(early_adopter[i], early_adopter[i+1]) for i in range(len(early_adopter)-1)]
dist

标签: pythonrecursion

解决方案


首先,您有时会写 user2,有时会写 usr2;

然后你有

  1. 在 follower_list 项目上循环
  2. 仅当您找到匹配项时才增加
  3. 限制为 3 深度。

这是您可以做什么的想法:

def get_distance(usr1, usr2):
    get_distance_with_depth(usr1, usr2, 0)
    
def get_distance_with_depth(usr1, usr2, depth): // inseert depth in reccursion
    if depth==3:
        return 0
    follower_list=[]
    path = 0
    for user in tweepy.Cursor(api.followers, user_id = usr1).items(4):
      follower_list.append(user.id)
    if usr2 in follower_list:
        path =+ 1
        return path
    else: //usr2 not in follower_list
        for subuser in follower_list: // loop on subusers
            distance = get_distance_with_depth(subuser, usr2, depth+1)
            if distance != 0: // found a match
                return distance+1 // add +1 only if you find a match
            // if not found, go on looping
        // if reaching here, no match was found
        return 0


   

推荐阅读