Reputation:
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?
Upvotes: 0
Views: 1551
Reputation: 133
import itertools
stuff = ["ab", "ls", "u"]
for i in range(len(stuff) + 1):
for x in itertools.permutations(stuff[:i]):
print(x)
But this solution show all permutations::
()
('ab',)
('ab', 'ls')
('ls', 'ab')
('ab', 'ls', 'u')
('ab', 'u', 'ls')
('ls', 'ab', 'u')
('ls', 'u', 'ab')
('u', 'ab', 'ls')
('u', 'ls', 'ab')
Upvotes: 0
Reputation: 29
As you are giving list with 3 elements permutations is giving you back result with all 3 elements.
You need to supply 1 element to get your ab
/ls
/u
in output.
You need to supply 2 element to get your ab ls
/ab u
in output.
So same program you can use by calling it with 1/2 elements in list.
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
stuff = ["ab", "ls"]
for subset in itertools.permutations(stuff):
concat = ""
for part in subset:
concat = concat + part
stuff = ["ls", "u"]
for subset in itertools.permutations(stuff):
concat = ""
for part in subset:
concat = concat + part
Upvotes: 1
Reputation: 1907
stuff = ["ab", "ls", "u"]
final_list = []
for subset in itertools.permutations(stuff):
concat = ""
for part in subset:
concat = concat + part
final_list.append(concat)
print(final_list)
['ab',
'abls',
'ablsu',
'ab',
'abu',
'abuls',
'ls',
'lsab',
'lsabu',
'ls',
'lsu',
'lsuab',
'u',
'uab',
'uabls',
'u',
'uls',
'ulsab']
Upvotes: 0
Reputation: 1978
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
Upvotes: 3