[Tutor] listing all combinations of elements of a list
keridee at jayco.net
Sun Dec 19 04:16:21 CET 2004
Am I wrong, or is that what the module sets is for? I don't remember if
python 2.3 has it, but python2.4 has it available.
>>> import sets
>>> s = sets.Set
>>> a = s([1,2,3])
Set([1, 2, 3])
Set([1, 2, 3, 4, 5])
> > def combination(items)
> > list = 
> > for i in range(0,len(items)):
> > for j in range(0,len(items)):
> for i in items:
> for j in items:
> Is both shorter and faster - no len() function calls.
> Or if you want to use indices:
> size = len(items) # only calculate once, it won't change!
> lst =  # don't use builtin function names for
> for i in range(0,size)
> for j in range(i+1,size)
> return lst
> That saves a lot of len() calls and a comparison.
> Also it avoids iterating over the whole list each time.
> > My problems with this code being that a) code I write is usually
> > inefficient, b) it doesn't extend to subsets of size > 2, and c) it
> > nested loops, which I have gathered from some previous discussions
> > this list to be less than ideal.
> I've tidied up a little but I think nested loops are a necessary evil
> this case - although somebody is sure to prove me wrong! :-)
> Alan G.
> Tutor maillist - Tutor at python.org
More information about the Tutor