使用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

首先,您有时编写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


最新更新