Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
69 views
in Technique[技术] by (71.8m points)

python - Another random tree generator

I would like to construct a random tree: for each node, there a random number of leaves is created.

I am almost there, but I don't understand why recursion is done only at the first leaf of a branch.

This is my code:

# 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

The result I have, though, is this: note that recursion is only at the first node of each branch, instead I want it for all nodes of the each branch.

enter image description here

Can you help me fix it and understand why ?

question from:https://stackoverflow.com/questions/65603136/another-random-tree-generator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...