Created
September 29, 2017 21:25
-
-
Save yhcharles/606d2a0f244db52181055da38a6f0f53 to your computer and use it in GitHub Desktop.
shows recursion using function and generator in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| class Node(object): | |
| def __init__(self, x): | |
| self.val = x | |
| self.left = None | |
| self.right = None | |
| def get_tree(): | |
| """ | |
| 3 | |
| / \ | |
| 1 4 | |
| / \ \ | |
| 0 2 5 | |
| """ | |
| node_list = [Node(i) for i in range(6)] | |
| node_list[3].left = node_list[1] | |
| node_list[3].right = node_list[4] | |
| node_list[1].left = node_list[0] | |
| node_list[1].right = node_list[2] | |
| node_list[4].right = node_list[5] | |
| return node_list[3] | |
| def recursive(root, f): | |
| if root is not None: | |
| recursive(root.left, f) | |
| f(root) | |
| recursive(root.right, f) | |
| def generator_v3(root): | |
| """ for python 3, with 'yield from' | |
| """ | |
| if root is not None: | |
| yield from generator_v3(root.left) | |
| yield root | |
| yield from generator_v3(root.right) | |
| def generator_v2(root): | |
| """ for python 2, without 'yield from' | |
| """ | |
| if root is not None: | |
| for node in generator_v2(root.left): | |
| yield node | |
| yield root | |
| for node in generator_v2(root.right): | |
| yield node | |
| def main(): | |
| def f(node): | |
| print(node.val) | |
| root = get_tree() | |
| print('recursive:') | |
| recursive(root, f) | |
| print('\ngenerator 2:') | |
| for node in generator_v2(root): | |
| f(node) | |
| print('\ngenerator 3:') | |
| for node in generator_v3(root): | |
| f(node) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment