views:

366

answers:

4

I'm trying to display all possible combinations of a list of numbers, for example if I have 334 I want to get:

3 3 4
3 4 3
4 3 3

I need to be able to do this for any set of digits up to about 12 digits long.

I'm sure its probably fairly simple using something like itertools.combinations but I can't quite get the syntax right.

TIA Sam

A: 

See this.

kprobst
+2  A: 

You want permutations, not combinations. See: http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python

>>> from itertools import permutations
>>> [a for a in permutations([3,3,4])]
[(3, 3, 4), (3, 4, 3), (3, 3, 4), (3, 4, 3), (4, 3, 3), (4, 3, 3)]

Note that it's permuting the two 3's (which is the correct thing mathematically to do), but isn't the same as your example. This will only make a difference if there are duplicated numbers in your list.

Seth
+9  A: 
>>> lst = [3, 3, 4]
>>> import itertools
>>> set(itertools.permutations(lst))
{(3, 4, 3), (3, 3, 4), (4, 3, 3)}
SilentGhost
+1, distinct permutations of a list. `set(list())` to the rescue again.
Seth
perfect thx :-)
Sam Machin
+1  A: 

without itertools

def permute(LIST):
    length=len(LIST)
    if length <= 1:
        yield LIST
    else:
        for n in range(0,length):
             for end in permute( LIST[:n] + LIST[n+1:] ):
                 yield [ LIST[n] ] + end

for x in permute(["3","3","4"]):
    print x

output

$ ./python.py
['3', '3', '4']
['3', '4', '3']
['3', '3', '4']
['3', '4', '3']
['4', '3', '3']
['4', '3', '3']
ghostdog74