I found myself using these 2 custom generators and thinking "there's got to be an itertools function or something that already does this! Didn't find any though. Am I missing something? Thanks!
def gothru(iters):
for i in iters:
for j in i:
yield j
def overnover(fn,startval):
val = startval
while True:
val = fn(val)
yield val
EDIT: i was later imagining how overnover could be used to generate the fibonacci sequence, and i realized that it would need to be generalized to allow the function to have more than one argument
def overnover(fn,*args):
while True:
args = fn(*args)
return args
then you could do:
fibInfo = overnover(lambda x,y: (x+y, x), 1, 1)
-> (2,1) ... (3, 2) ... (5, 3) ... (8, 5) ... and then:
fib = imap(lambda x:x[0], fibInfo)
-> 2 ... 3 ... 5 ... 8 ...
thanks guys!
The first one is chain.from_iterable.
The closest thing to overnover is something like tabulate:
def tabulate(function, start=0):
"Return function(0), function(1), ..."
return imap(function, count(start))
which is a special case of your function where it outputs sequential numbers. count also takes a step, so you could generalize this to
def tabulate(function, start=0, step=1):
"Return function(0), function(0+step), ..."
return imap(function, count(start, step))
Here is a version of overnover that would let you send values into the sequence:
def overnover(fn, val):
while True:
val = fn(val)
val = (yield val) or val
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With