python - 使用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;
然后你有
- 在 follower_list 项目上循环
- 仅当您找到匹配项时才增加
- 限制为 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
推荐阅读
- c# - 从 asp.net 核心应用程序启动 linux 进程失败(找不到文件)
- excel - 如何使用 VBA 在 Excel 中将单列转换为多个不均匀的列/行
- r - 设置开始计数的数字
- uml - 如何在 UML 序列图中表示来自传感器的反馈
- jenkins - 使用 SSH 在远程主机上执行 Shell 脚本
- flutter - 如何将数据从无状态小部件发送到有状态小部件?
- css - 将 svg 图像定位在 span 下
- javascript - 将 Java SOAP 请求翻译成 Javascript?
- flutter - 是否有显示 360 度图像的颤振小部件?
- swift - 使用 Alamofire 发出获取请求时,除了 `isSuccess` 之外,我还应该使用什么其他成员?