How to return instead of print

Viewed 74

I get the desired result from using print() but I want the same result when using a return. How can I change this to a return? When I do it only returns the first key, value where I want to have the four that are in the BST.

 def inOrder(self, aNode):
       if aNode:
        self.inOrder (aNode.leftChild)
        print (aNode.key + ' ' + aNode.payload +'\n')
        self.inOrder (aNode.rightChild)

The result I am looking for is to have four keys followed by their value.

1 Answers

To do exactly what you want, you need to use the yield keyword (details for the yield from statement here)

 def inOrder(self, aNode):
       if aNode:
        yield from self.inOrder(aNode.leftChild)
        yield (aNode.key, aNode.payload)
        yield from self.inOrder(aNode.rightChild)

Which will return a generator, you can "expand" it by using list(inOrder(...))

You could also have a dedicated argument that you would update as you go through:

 def inOrder(self, aNode, res=[]):
       if aNode:
        self.inOrder(aNode.leftChild, res)
        res.append((aNode.key, aNode.payload))
        self.inOrder(aNode.rightChild, res)

Which will provide similar results.

Related