Last active
October 15, 2022 16:24
-
-
Save EteimZ/f8430ed510f0edb48e4d36b13e23f141 to your computer and use it in GitHub Desktop.
snippets of python generators
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 infCount(): | |
| """ | |
| Infinite counter | |
| """ | |
| i = 0 | |
| while True: | |
| yield i | |
| i += 1 | |
| # Usage | |
| inf = infCount() | |
| next(inf) # 0 | |
| next(inf) # 1 | |
| next(inf) # 2 | |
| def genFib(): | |
| """ | |
| Fibonacci generator | |
| """ | |
| a, b = 0, 1 | |
| while True: | |
| yield a | |
| a, b, = b, a + b | |
| fib = genFib() | |
| next(fib) # 0 | |
| next(fib) # 1 | |
| next(fib) # 1 | |
| next(fib) # 2 | |
| next(fib) # 3 |
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 infCount(): | |
| """ | |
| Infinite counter generator | |
| that takes in a value | |
| """ | |
| i = 0 | |
| while True: | |
| val = (yield i) | |
| if val is not None: | |
| i += val | |
| else: | |
| i += 1 | |
| # Usage | |
| inf = infCount() | |
| next(inf) # 0 | |
| next(inf) # 1 | |
| next(inf) # 2 | |
| inf.send(8) # give generator a value | |
| next(inf) # 10 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment