about list

Jeffrey Schwab jeff at schwabcenter.com
Sun Nov 20 22:56:51 EST 2005


rurpy at yahoo.com wrote:
> Shi Mu wrote:
> 
>>How to run a function to make [1,2,4] become [[1,2],1,4],[2,4]]?
>>Thanks!
> 
> 
> You want [[1,2],[1,4],[2,4]]?  That is, all combinations of 2 items
> from
> the list?  You might want to look at:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465
> 
> 
>>>>import * from xpermutations
>>>>[x for x in UniqueCombinations ([1,2,4], 2)]
> 
> [[1, 2], [1, 4], [2, 4]]
> 
> That web page also gives urls to other recipies that do the same thing.

Dang, that's better than my version.

	$ ./combinations.py 2 1 2 4
	[['1', '2'], ['1', '4'], ['2', '4']]

def combinations( universe, n=None ):

         """
         Return all possible combinations of length "n," where the
         elements of each combination are taken from the list "universe."
         """

         result = []

         if n == None:
                 n = len( universe )

         if n > len( universe ):
                 # No combination of elements can have cardinality
                 # greater than universe, which is by definition the list
                 # of all possible elements.
                 pass
         elif n < 0:
                 # No combination can have negative cardinaltiy.
                 pass
         elif n == 0:
                 # Only the empty combination has cardinality 0.
                 result.append( [ ] )
         else:   # 0 < n <= len( universe )
                 for i in xrange( len( universe ) ):
                         elem = universe[i]
                         post = universe[i+1:]
                         for c in combinations( post, n - 1 ):
                                 choice = [ elem ]
                                 choice.extend( c )
                                 result.append( choice )

         return result

if __name__ == "__main__":

         import sys

         if len( sys.argv ) < 2:
                 sys.stderr.write(
                         "usage: %s <n> [elements ...]\n" % sys.argv[0] )
                 sys.exit(1)

         n = int( sys.argv[1] )
         print repr( combinations( sys.argv[2:], n ) )



More information about the Python-list mailing list