import itertools
You can do, using itertools permutations & combinations:
def string_set(x):
arr = [''.join(l) for i in range(len(x)) for l in itertools.combinations(x, i+1)]
reslist=[]
for eachpermut in arr:
for each in [''.join(eachpermut) for eachpermut in list(itertools.permutations(eachpermut))]:
reslist.append(each)
return reslist
If you like everything in one line:
def string_set(x):
return [each for eachpermut in [''.join(l) for i in range(len(x)) for l in itertools.combinations(x, i+1)] for each in [''.join(eachpermut) for eachpermut in list(itertools.permutations(eachpermut))]]
string_set('abc')
returns:
['a',
'b',
'c',
'ab',
'ba',
'ac',
'ca',
'bc',
'cb',
'abc',
'acb',
'bac',
'bca',
'cab',
'cba']
If you don't want to import itertools
, you can just use their permutations
functions only:
def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = list(range(n))
cycles = list(range(n, n-r, -1))
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
Then just do permutations
instead of itertools.permutations
in the above code.
Can do the same with combinations
.