简体   繁体   English

使用递归 function 和 python 找到路径

[英]find the path with a recursive function with python

I am trying to create this function that will help me to look into the list of friend and the friends or the friends' lists in order to know how many steps or list of friends I should look for to find the consecutive user in my list of early_adopters .我正在尝试创建这个 function,它将帮助我查看朋友列表和朋友列表,以便了解我应该寻找多少步骤或朋友列表才能在我的列表中找到连续用户early_adopters

What I have so far:到目前为止我所拥有的:

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

First of all you wrote sometimes user2 and sometimes usr2;首先,您有时会写 user2,有时会写 usr2;

Then you have然后你有

  1. to loop on follower_list items在 follower_list 项目上循环
  2. to increment only if you found a match仅当您找到匹配项时才增加
  3. to limit to 3 depth.限制为 3 深度。

Here is an idea of what you could do:这是您可以做什么的想法:

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


   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM