简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM