def find_generations(container, with_data=False):
    """
    A generation is the set of stochastic variables that only has parents in
    previous generations.
    """
    generations = []
    generations.append(set())
    all_children = set()
    if with_data:
        stochastics_to_iterate = (container.stochastics | container.
            observed_stochastics)
    else:
        stochastics_to_iterate = container.stochastics
    for s in stochastics_to_iterate:
        all_children.update(s.extended_children & stochastics_to_iterate)
    generations[0] = stochastics_to_iterate - all_children
    children_remaining = True
    gen_num = 0
    while children_remaining:
        gen_num += 1
        generations.append(set())
        for s in generations[gen_num - 1]:
            generations[gen_num].update(s.extended_children &
                stochastics_to_iterate)
        thisgen_children = set()
        for s in generations[gen_num]:
            thisgen_children.update(s.extended_children &
                stochastics_to_iterate)
        generations[gen_num] -= thisgen_children
        if len(thisgen_children) == 0:
            children_remaining = False
    return generations
