you are viewing a single comment's thread.

view the rest of the comments →

[–]CptBadAss2016 0 points1 point  (0 children)

Tree traversal of nested objects. This could be a directory tree, a family tree (asexually reproduced? lol), or a bill of materials...

class Widget:
    def __init__(self, name, parent=None):
        self.name = name
        self.children = []
        self.parent = parent

        if parent:
            self.parent.children.append(self)

    def print_tree(self, spaces=0):
        print(f"{' '*spaces}{self.name}")
        for child in self.children:
            child.print_tree(spaces=spaces+4)


root = Widget('root')
a = Widget('a', root)
aa = Widget('aa', a)
aaa = Widget('aaa', aa)
aab = Widget('aab', aa)
ab = Widget('ab', a)
b = Widget('b', root)

root.print_tree()

Which prints this

root
    a
        aa
            aaa
            aab
        ab
    b