Skip to content

Instantly share code, notes, and snippets.

@danielSanchezQ
Last active July 26, 2016 10:35
Show Gist options
  • Save danielSanchezQ/49976d639a97a9e5a1b3ce3d313ded93 to your computer and use it in GitHub Desktop.
Save danielSanchezQ/49976d639a97a9e5a1b3ce3d313ded93 to your computer and use it in GitHub Desktop.
Python generators cool stuff
from itertools import *
from operator import *
def fibogen():
a,b = 1,1
yield a
yield b
while True:
res = a+b
a, b = b, res
yield res
#Haskell take 5 [1..] -> [1,2,3,4,5]
def take(n, gen, consume = False):
if not consume:
_, it = tee(gen)
else:
it = gen
for _ in range(n):
yield next(it)
def myZip(*args):
iterators = map(iter, args)
while True:
try:
yield tuple(x.next() for x in iterators)
except:
break
# def zipWith(f, *args):
# yield from map(f, *args)
# Python 2 example
def zipWith(f, *args):
return (f(*x) for x in myZip(*args))
if __name__ == "__main__":
fibonnacci = fibogen()
print("Coger 10 elementos de un generador de fibonacci y consumirlos (10)")
print(list(take(10, fibonnacci, consume=True)))
print("Sumar por pares de la secuencia de fibonacci hasta que estos sean mayores de 10000")
print(list(takewhile(lambda x: x < 10000, zipWith(add, *tee(fibogen())))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment