There are some problems here:
- you use
[s.keys()[0]]as a way to find the "root" of the tree. However, note that the dictionaries are unordered (yes, CPython-3.6 dictionaries use the insertion order, but this is considered an implementation detail), so there is no guarantee that it [s.keys()[0]]is actually the root; and - you do a single pass through the dictionary, but again, since the dictionaries are disordered, it is not guaranteed that the parent will be assigned already.
, . , , . :
nonroots = {c for cs in s.values() for c in cs}
, , , , , :
roots = [k for k in s if k not in nonroots]
0, :
levels[0] = roots
:
, , .
next_gen = [c for k in prev_gen for c in s.get(k,())]
, : , . , :
nonroots = {c for cs in s.values() for c in cs}
level = [k for k in s if k not in nonroots]
generation = 0
result = {}
while level:
result[generation] = level
generation += 1
level = [c for k in level for c in s.get(k,())]
, result - , .
, , 0, , i, i-1 ( i > 0), , :
nonroots = {c for cs in s.values() for c in cs}
level = [k for k in s if k not in nonroots]
result = []
while level:
result.append(level)
level = [c for k in level for c in s.get(k,())]
:
>>> result
[['a'], ['b'], ['c', 'd'], ['i', 'e', 'l'], ['f', 'g', 'h']]
()
, (), . , :
def get_levels(tree, roots):
result = []
roots = list(roots)
while roots:
result.append(roots)
roots = [c for k in roots for c in tree.get(k,())]
return result
. , (s) :
>>> get_levels(s, ['a'])
[['a'], ['b'], ['c', 'd'], ['i', 'e', 'l'], ['f', 'g', 'h']]
>>> get_levels(s, ['c'])
[['c'], ['i']]
>>> get_levels(s, ['i','l'])
[['i', 'l']]
>>> get_levels(s, ['i','e'])
[['i', 'e'], ['f', 'g', 'h']]