Search code examples
pythonpython-3.xpython-itertools

Get all permutations of a list in python without duplicates?


I am trying to write a script that gets a set of strings-

["ab", "ls", "u"]

Then creates every possible combination of them, but doesn't necessarily use all of them. I want possible outputs for the above example to be:


ab
ab ls
ab ls u
ab u ls
ab u

ls
ls ab
ls ab u
ls u ab
ls u

u
u ls
u ls ab
u ab ls
u ab

My script, having removed the other things it does:

stuff = ["ab", "ls", "u"]

for subset in itertools.permutations(stuff):
    concat = ""
    for part in subset:
        concat = concat + part

    #the rest of my script now uses this data

It returns:

ablsu
abuls
lsabu
lsuab
uabls
ulsab

How would I make it return what I want?


Solution

  • You can use combinations and permutations together. This should be able to get you going

    a = ["ab", "ls", "u"]
    for i in range(1, len(a)+1):
        for comb in combinations(a, i):
            for perm in permutations(comb):
                print(perm)
    

    Output:

    ('ab',)
    ('ls',)
    ('u',)
    ('ab', 'ls')
    ('ls', 'ab')
    ('ab', 'u')
    ('u', 'ab')
    ('ls', 'u')
    ('u', 'ls')
    ('ab', 'ls', 'u')
    ('ab', 'u', 'ls')
    ('ls', 'ab', 'u')
    ('ls', 'u', 'ab')
    ('u', 'ab', 'ls')
    ('u', 'ls', 'ab')
    

    You can handle comb how ever you see fit