Combinations or Permutations

Seth Leija fazzitron at gmail.com
Mon Sep 20 17:57:48 EDT 2010


On Sep 20, 3:08 pm, Mark Lawrence <breamore... at yahoo.co.uk> wrote:
> On 20/09/2010 21:54, Seth Leija wrote:
>
>
>
>
>
> > I need to know how to generate a list of combinations/permutations
> > (can't remember which it is). Say I have a list of variables:
>
> > [a,b,c,d,...,x,y,z]
>
> > I am curious if there is an optimized way to generate this:
>
> > [[a,b],[a,c],[a,d],...,[x,z],[y,z]]
>
> > I currently have an iteration that does this:
>
> > #list.py
>
> > from math import *
>
> > list1=['a','b','c','d','e']
> > list2=[]
> > length=len(list1)
>
> > for it1 in range(0 ,length):
> >      for it2 in range(it1+1, length):
> >          list2.append([list1[it1],list1[it2]])
>
> > print list2
>
> > However, this is one of the slowest parts of my function (beaten only
> > by variable instantiation). I posted this on another forum looking to
> > see if there was a different method completely. They said that my
> > method was about as simple as it could get, but I might be able to
> > find out how to optimize my code here.
>
> > Thanks in advance.
>
> Check the docs for the itertools module.
>
> Cheers.
>
> Mark Lawrence.

That works! That made my function significantly faster! It's still
slower than I would like it, but this is enough for now. Thank you so
much!



More information about the Python-list mailing list