Skip to content Skip to sidebar Skip to footer

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 import

Solution 1:

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.


Solution 2:

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')]

Solution 3:

Given that other languages are acceptable:

#!/usr/bin/perl

use strict; use warnings;
use Algorithm::Combinatorics qw(permutations);

my $data = [ qw( hel lo bye ) ];
my $it = permutations($data);

while ( my $p = $it->next ) {
    print @$p, "\n";
}
hellobye
helbyelo
lohelbye
lobyehel
byehello
byelohel

Solution 4:

a = ['hel', 'lo', 'bye']
print '\n'.join(''.join(x) for x in itertools.permutations(a, 2))

Solution 5:

Easy in python with itertools.

Here is the token permutation example:

import itertools

tokens = ["hel", "lo", "bye"]

for i in range(1, len(tokens) + 1):
    for p in itertools.permutations(tokens, i):
        print "".join(p)

Alternatively, this treats each character as a token:

import itertools

tokens = ["hel", "lo", "bye"]

chars = "".join(tokens)
for i in range(1, len(chars) + 1):
    for p in itertools.permutations(chars, i):
        print "".join(p)

Post a Comment for "Generate All Possible Strings From A List Of Token"