4 ms·
Not entirely mine but beautiful nonetheless: @dataclass class Node: id: str children: List[Node] = field(default_factory=list)
by delaaxe 6y ago
Not entirely mine but beautiful nonetheless:
@dataclass
class Node:
id: str
children: List[Node] = field(default_factory=list)
# beautiful Python: traverse a tree depth-first, pre-order (stack based)
def __iter__(self):
stack = [self]
while stack:
node = stack.pop()
yield node
stack = node.children + stack
- heavenlyblue 6y agoYou should really use deque for the stack
- nivethan 6y agoWhy?
- comfydragon 6y agoProbably just an efficiency argument, since deque is designed to be efficient when used as a stack/queue. https://docs.python.org/3.8/library/collections.html#collections.deque https://docs.python.org/3.8/library/collections.html#collect...
- delaaxe 6y agoIt's what I did in other parts of the project but I haven't noticed any performance increase. I guess standard lists are already fast enough for implementing stacks.