Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Co-routines

Reply
Thread Tools

Re: Co-routines

 
 
Alan Kennedy
Guest
Posts: n/a
 
      07-17-2003
http://www.velocityreviews.com/forums/(E-Mail Removed) 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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off




Advertisments