Generate all combinations of strings and their substrings in a set -- python

1.2k views Asked by At

I want to get all combinations of of strings from a set of strings. For Example:

permut = set()
permut.add("D")
permut.add("C")

def getAllKombos(stuff):
    returnvalue = set()
    for L in range(0, len(stuff) + 1):
        for subset in itertools.combinations(stuff, L):
            for i in subset:
                x = x + (str(i))
                returnvalue.add(x)
            x = ""
    return returnvalue

print getAllKombos(permut)

my output is:

set(['C', 'D', 'CD'])

but I need

set(['C', 'D', 'CD', 'DC'])

I don't get what I'm doing wrong

1

There are 1 answers

0
Anthony Dito On BEST ANSWER
import itertools

permut = set()
permut.add("D")
permut.add("C")

def getAllKombos(stuff):
    returnvalue = set()
    for L in range(0, len(stuff) + 1):
        for subset in itertools.permutations(stuff, L):
            for i in subset:
                x = x + (str(i))
                returnvalue.add(x)
            x = ""
    return returnvalue

print getAllKombos(permut)

This code now works, all you had to do is switch combination to permutation.