Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate all possible strings from a list of token

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.

like image 756
lbedogni Avatar asked Oct 30 '10 16:10

lbedogni


2 Answers

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')]
like image 123
Bertrand Marron Avatar answered Oct 12 '22 23:10

Bertrand Marron


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.

like image 39
Sven Marnach Avatar answered Oct 12 '22 23:10

Sven Marnach