Last active
April 20, 2018 11:49
-
-
Save shivamMg/7d5b10a8f0948a9ec767135be1eee40d to your computer and use it in GitHub Desktop.
Arithmetic Progression with a Closure, and a Generator
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
| def arith(a: 'initial term', d: 'common difference'): | |
| """Returns initial and subsequent arithmetic progression terms""" | |
| current = a - d | |
| def _(): | |
| nonlocal current | |
| current += d | |
| return current | |
| return _ | |
| def arith_gen(a, d): | |
| """Same function as above except it uses generators""" | |
| current = a | |
| while True: | |
| yield current | |
| current += d | |
| if __name__ == '__main__': | |
| a = arith(1, 2) | |
| print(a()) | |
| print(a()) | |
| print(a()) | |
| a = arith_gen(1, 2) | |
| print(next(a)) | |
| print(next(a)) | |
| print(next(a)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment