Re: Co-routines

Discussion in 'Python' started by Alan Kennedy, Jul 17, 2003.

  1. Alan Kennedy

    Alan Kennedy Guest

    wrote:

    > I want to execute these functions in
    > "lock-step", so that the output looks like:
    >
    > 1-1
    > 2-2
    > 1-2
    > 2-2
    > 1-3
    > 2-3


    Have you made a mistake in this output? Should it be this?

    1-1
    2-1
    1-2
    2-2
    1-3
    2-3

    If yes, how about this?

    #-------------------------
    import itertools

    def seq(which, iterable):
    for i in iterable:
    yield "%d-%d" % (which, i)

    times = [1,2,3]

    seq1 = seq(1, times)
    seq2 = seq(2, times)

    for v1, v2 in itertools.izip(seq1, seq2):
    print v1
    print v2
    #--------------------------

    If you want to generalise the number of iterators, how about this?

    #--------------------------
    def lizip(iterables):
    iterables = map(iter, iterables)
    while True:
    result = [i.next() for i in iterables]
    yield tuple(result)

    def seq(which, iterable):
    for i in iterable:
    yield "%d-%d" % (which, i)

    y = [1,2,3] ; max_x = 5

    iters = [seq(x, y) for x in range(1, max_x+1)]

    for vertslice in lizip(iters):
    for v in vertslice:
    print v
    #--------------------------

    Note that these examples don't use "coroutines". Instead they use
    python generators, which are classified as "semi-coroutines".

    --
    alan kennedy
    -----------------------------------------------------
    check http headers here: http://xhaus.com/headers
    email alan: http://xhaus.com/mailto/alan
    Alan Kennedy, Jul 17, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Andrew Rich

    Proper serial routines ?

    Andrew Rich, Oct 4, 2003, in forum: Perl
    Replies:
    1
    Views:
    439
    Al Tobey
    Oct 24, 2003
  2. Soenke
    Replies:
    0
    Views:
    548
    Soenke
    Dec 28, 2005
  3. Matthew Hood

    How to create global Funtions & Routines

    Matthew Hood, Jun 24, 2003, in forum: ASP .Net
    Replies:
    2
    Views:
    1,915
    Matthew Hood
    Jun 25, 2003
  4. Keith A. Rowe
    Replies:
    2
    Views:
    293
    Keith A. Rowe
    Feb 14, 2004
  5. tshad
    Replies:
    2
    Views:
    698
    tshad
    Jan 28, 2005
Loading...

Share This Page