William Stein wrote:
> On Fri, Jan 30, 2009 at 4:23 AM, Alasdair <amc...@gmail.com> wrote:
>> I was recently experimenting with iterators over permutations, and
>> using them to find if a graph was Hamiltonian.  This was done by brute
>> force - no clever tricks - simply by trying every possible permutation
>> of vertices and seeing if each was a cycle.
>>
>> Now there seem to be (at least) two ways of iteration over
>> permutations:
>>
>> v=Permutations(range(n))
>> vp=v.first()
>> ...more code here...
>> for i in range(factorial(n)):
>>   vp=v.next(vp)
>>
>> and
>>
>> v=(p for p in Permutations(range(n)))
>> ...more code here...
>> for i in range(factorial(n)):
>>   vp=v.next()
>>
>> Now the second is much much faster than the first.  On my rather
>> elderly laptop, with n=7, the second code takes less then 3 seconds,
>> and the first code takes nearly 82 seconds!
>>
>> But here's the thing: when I tried to compile my function (as a spyx
>> file), there was an error converting Pyrex to C when using the second
>> iteration; I was stuck with the slower first method (and importing
>> Permutations from sage.combinat.permutation).
>>
>> So how can I obtain a fast iteration over permutations in compiled
>> code?
> 
> Cython doesn't support closures, so you can use the second.  Yes,
> v=(p for p in Permutations(range(n))) is a closure.
> 
> Use this instead of either of your loops:
> 
>     v=Permutations(range(n)).__iter__()
>     ...
>     for i in range(factorial(n)):
>         vp = v.next()


Is there a reason you didn't use the less scary alternative below, other 
than avoiding one function call?

v = iter(Permutations(range(n)))

Jason



--~--~---------~--~----~------------~-------~--~----~
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
URLs: http://www.sagemath.org
-~----------~----~----~----~------~----~------~--~---

Reply via email to