Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Re: Co-routines (http://www.velocityreviews.com/forums/t319816-re-co-routines.html)

 Alan Kennedy 07-17-2003 02:19 PM

Re: Co-routines

thewrights@ozemail.com.au 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

#-------------------------
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
#--------------------------

#--------------------------
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
-----------------------------------------------------