fork download
  1. def split_tree(tree, level=0):
  2. for name, branch in tree.items():
  3. if branch:
  4. paths = split_tree(branch, level - 1)
  5. if level > 0:
  6. yield from ([name, *path] for path in paths)
  7. else:
  8. yield [name, [node for path in paths for node in path]]
  9. else:
  10. yield [name]
  11.  
  12. tree = {
  13. 'ROOT': {
  14. 'B': {
  15. 'E': {},
  16. 'F': {}
  17. },
  18. 'C': {},
  19. 'D': {
  20. 'H': {},
  21. 'I': {
  22. 'J': {},
  23. 'K': {}
  24. }
  25. }
  26. }
  27. }
  28. print(*split_tree(tree, 1), sep='\n')
  29. print()
  30. print(*split_tree(tree, 2), sep='\n')
Success #stdin #stdout 0.03s 9640KB
stdin
Standard input is empty
stdout
['ROOT', 'B', ['E', 'F']]
['ROOT', 'C']
['ROOT', 'D', ['H', 'I', ['J', 'K']]]

['ROOT', 'B', 'E']
['ROOT', 'B', 'F']
['ROOT', 'C']
['ROOT', 'D', 'H']
['ROOT', 'D', 'I', ['J', 'K']]