On Oct 23, 12:27 am, Rolandb <rola...@planet.nl> wrote:
> Hi, look at the following simple routine.
>
> def why():
>
>     test=((k2,k1) for k1 in xrange(2,4) for k2 in xrange(1,k1) if
> gcd(k1,k2)==1)
>
>     print [t for t in test]
>     print [t for t in test]
>
>     return
>
> why()
> [(1, 2), (1, 3), (2, 3)]
> []
>
> It seems that "test" can only be used once.

Yes, this is how python works. You don't tell the generator to "start
over" in between (there is no way to do that. You should just recreate
it)
Perhaps writing out the generator construction explains why this is
the right thing to do, even if it leads to surprising results in your
example:

def maketest():
    for k1 in xrange(2,4):
        for k2 in xrange(1,k1):
            if gcd(k1,k2)==1:
                yield (k2,k1)

test=maketest()

L=[]
try:
    while true:
        L.append(test.next())
except StopIteration:
    pass
print L

L=[]
try:
    while true:
        L.append(test.next())
except StopIteration:
    pass
print L

-- 
To post to this group, send email to sage-support@googlegroups.com
To unsubscribe from this group, send email to 
sage-support+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org

Reply via email to