1

This works fine with Python 3.5 .I understand yield from is not available in python 2.7. How can I implement the depth_first() function using python 2.7?

The following solution did not help me: Converting "yield from" statement to Python 2.7 code

class Node:
 def __init__(self, value):
    self._value = value
    self._children = []

 def __repr__(self):
    return 'Node({!r})'.format(self._value)

 def add_child(self, node):
    self._children.append(node)

 def __iter__(self):
    return iter(self._children)

 def depth_first(self):
    yield self
    for c in self:
        yield from c.depth_first()

# Example
if __name__ == '__main__':
    root = Node(0)
    child1 = Node(1)
    child2 = Node(2)
    root.add_child(child1)
    root.add_child(child2)
    child1.add_child(Node(3))
    child1.add_child(Node(4))
    child2.add_child(Node(5))
    for ch in root.depth_first():
        print(ch)

This is the expected output:

Node(0), Node(1), Node(3), Node(4), Node(2), Node(5)
martineau
  • 119,623
  • 25
  • 170
  • 301
Joe_12345
  • 589
  • 2
  • 7
  • 19

1 Answers1

1

Convert yield from into a for-loop with plain yield.

Convert class Node: into class Node(object): to ensure you get a new-style class.

The code now works in Python 2.7.

class Node(object):
 def __init__(self, value):
    self._value = value
    self._children = []

 def __repr__(self):
    return 'Node({!r})'.format(self._value)

 def add_child(self, node):
    self._children.append(node)

 def __iter__(self):
    return iter(self._children)

 def depth_first(self):
    yield self
    for c in self:
        for n in c.depth_first():
            yield n

# Example
if __name__ == '__main__':
    root = Node(0)
    child1 = Node(1)
    child2 = Node(2)
    root.add_child(child1)
    root.add_child(child2)
    child1.add_child(Node(3))
    child1.add_child(Node(4))
    child2.add_child(Node(5))
    for ch in root.depth_first():
        print(ch)
wim
  • 338,267
  • 99
  • 616
  • 750
  • Note: this only works for trivial uses of `yield from`. If the caller is using `g.send` or other generator-specific functions, it does not. – o11c Aug 15 '17 at 00:46