微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

另一个随机树生成器

如何解决另一个随机树生成器

我想构造一个随机树:对于每个节点,都会创建随机数量的叶子。

我快到了,但我不明白为什么递归只在分支的第一片叶子上进行。

这是我的代码

# init,total_staff is the leaves counter
g = nx.DiGraph()
g.add_node(0)
total_staff = 0

# help function to create a group of leaves
# (the number of leaves will follow a given prob distribution)

def makeTeam():
    
    global total_staff
    
    # number of people reporting to root
    team_size = random.choices(team_population,weights = optimal_size_weight,k=1)[0]
    
    team = []
    for _ in range(team_size):
        total_staff += 1
        team_id = total_staff
        team.append(team_id)
    
    return team

# function to create a tree (representing an organisation)
def buildOrganisation(root):
    
    global total_staff
    if total_staff > 25:
        return g

    team = makeTeam()

    for team_id in team:
        print('creating sub ',root,team_id,team)
        g.add_edge(root,team_id)
        buildOrganisation(team_id) # this is the point I don't get: I expect recursion to be done for each team_id...
    
    return g

不过,我得到的结果是: 请注意,递归仅在每个分支的第一个节点,而不是每个分支的所有节点。

enter image description here

你能帮我修复它并理解原因吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。