2
\$\begingroup\$

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)
asked Jan 11, 2018 at 23:53
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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)
answered Jan 12, 2018 at 2:18
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.