I have a list of tokens, like:
hel
lo
bye
and i want to generate all the possible combinations of such strings, like:
hello
lohel
helbye
byehel
lobye
byelo
Language is not important, any advice?
I found Generating permutations using bash, but this makes permutation on a single line.
itertools.permutations
can do that for you.
>>> l = ['hel', 'lo', 'bye']
>>> list(itertools.permutations(l, 2))
[('hel', 'lo'), ('hel', 'bye'), ('lo', 'hel'), ('lo', 'bye'), ('bye', 'hel'), ('bye', 'lo')]
Or if you want combinations, you can use itertools.combinations
.
>>> l = ['hel', 'lo', 'bye']
>>> list(itertools.combinations(l, 2))
[('hel', 'lo'), ('hel', 'bye'), ('lo', 'bye')]
Your example can be written in Python as
from itertools import combinations
print list(combinations(["hel", "lo", "bye"], 2))
To combine the output to strings again:
print ["".join(a) for a in combinations(["hel", "lo", "bye"], 2)]
If you interested in the actual implementation of this function, have a look at the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With