On Mon, 06 Apr 2009 20:05:51 -0400, Neal Becker wrote:

> I'm trying to make a multiplexor and demultiplexor, using generators. 
> The multiplexor will multiplex N sequences -> 1 sequence  (assume equal
> length). The demultiplexor will do the inverse.
> 
> The mux seems easy enough:
> 
> -----------------------
> def mux (*ranges):
>     iterables = [iter (r) for r in ranges] while (True):
>         for i in (iterables):
>             yield i.next()


This is like a zip, and can be re-written using itertools.izip.

def mux(*iterables):
    for i in itertools.izip(*iterables):
        for item in i:
            yield item


The demuxer can't be an iterator, since it needs to run through the 
entire collection.

def demux(it, n):
    collectors = [[] for i in xrange(n)]
    i = 0
    for item in it:
        collectors[i].append(item)
        i = (i+1) % n
    return tuple([iter(x) for x in collectors])



-- 
Steven

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to