Skip to content

Instantly share code, notes, and snippets.

@EteimZ
Last active October 15, 2022 16:24
Show Gist options
  • Select an option

  • Save EteimZ/f8430ed510f0edb48e4d36b13e23f141 to your computer and use it in GitHub Desktop.

Select an option

Save EteimZ/f8430ed510f0edb48e4d36b13e23f141 to your computer and use it in GitHub Desktop.
snippets of python generators
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
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