Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there already python generators that do these basic things?

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!

like image 626
murftown Avatar asked Sep 14 '26 08:09

murftown


1 Answers

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
like image 88
agf Avatar answered Sep 16 '26 23:09

agf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!