I have an array called nodes
that contains a list of Node
objects. The list is sorted in depth-first order. I have a function called build_undirected_tree
that assigns the parent
value and creates a list of children
for each Node
in the list.
I'm not satisfied with the need for using the idx
array to circumvent Python's lack of pass-by-reference on primitive-type arguments and I'm wondering if there's a conceptually simpler way to accomplish the same thing.
class Node(object):
def __init__(self, child_count):
self.child_count = child_count
'''
This is a depth-first iterator. The weird `idx` array is used because
integers cannot be pass-by-reference.
'''
def node_iterator(nodes, idx=None, parent=None):
if idx is None:
idx = [0]
node = nodes[idx[0]]
yield (node, parent)
for i in range(node.child_count):
idx[0] += 1
yield from node_iterator(nodes, idx, node)
def build_undirected_tree(nodes):
for (node, parent) in node_iterator(nodes):
node.parent = parent
node.children = []
if parent is not None:
parent.children.append(node)
nodes = [...]
# Populate nodes from a file.
build_undirected_tree(nodes)
1 Answer 1
I believe you can get a similar result by creating and passing around an iterator on the nodes
list:
def node_iterator(nodes, nit=None, parent=None):
if nit is None:
nit = iter(nodes)
node = next(nit)
yield (node, parent)
for i in range(node.child_count):
yield from node_iterator(nodes, nit, parent=node)