some sort of permutations...

Jack Diederich jack at performancedrivers.com
Tue Apr 12 09:34:06 EDT 2005


On Tue, Apr 12, 2005 at 08:41:15AM -0400, Bill Mill wrote:
> On Apr 12, 2005 2:37 AM, Fredrik Lundh <fredrik at pythonware.com> wrote:
> > "Bernard A." wrote:
> > 
> > > i'm looking for a way to have all possible length fixed n-uples from a
> > > list, i think generators can help, but was not able to do it myself,
> > > maybe some one could point me out to an idea to do it ?
> > 
> > did you try googling for "python permutations" ?
> > 
> > here's the first hit:
> > 
> >     http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465
> > 
> 
> I've used that recipe a significant amount, and I feel like its
> recursion really slows it down (but I haven't been profiled it). Does
> anyone know of a non-recursive algorithm to do the same thing?

If you need the speed probstat.sf.net has permutations, combinations,
and cartesian products written in C.  I'm the author and I use pure-python
versions when I know I'm just doing small lists (to avoid a dependency).

>From your original problem it looks like you want a combination, not
a permutation.  Combinations don't care about order (just unique sets).

>>> import probstat
>>> for (item) in probstat.Combination([0,1,2,3,4], 3):
...   print item
... 
[0, 1, 2]
[0, 1, 3]
[0, 1, 4]
[0, 2, 3]
[0, 2, 4]
[0, 3, 4]
[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]

-jackdied



More information about the Python-list mailing list