Generate all possible lines from the token list

I have a list of tokens, for example:

hel
lo
bye

and I want to generate all possible combinations of such strings, for example:

hello
lohel
helbye
byehel
lobye
byelo

Language is not important, any tips?

I found Creating permutations using bash , but it does the permutation on one line.

+5
source share
8 answers

Your example can be written in Python as

from itertools import combinations
print list(combinations(["hel", "lo", "bye"], 2))

To combine output with strings again:

print ["".join(a) for a in combinations(["hel", "lo", "bye"], 2)]

If you are interested in actually implementing this feature, check out the documentation .

+14
source

itertools.permutations can do it for you.

>>> l = ['hel', 'lo', 'bye']
>>> list(itertools.permutations(l, 2))
[('hel', 'lo'), ('hel', 'bye'), ('lo', 'hel'), ('lo', 'bye'), ('bye', 'hel'), ('bye', 'lo')]

, , itertools.combinations.

>>> l = ['hel', 'lo', 'bye']
>>> list(itertools.combinations(l, 2))
[('hel', 'lo'), ('hel', 'bye'), ('lo', 'bye')]
+5

, :

#!/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
+3
a = ['hel', 'lo', 'bye']
print '\n'.join(''.join(x) for x in itertools.permutations(a, 2))
+2

python itertools.

:

import itertools

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

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

, :

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)
+1

Python permutations.:)

+1

, permutations:

from itertools import permutations

# easy way to make a list for words
words = 'hel lo bye'.split()

# fetch two-word permutations, joined into a string
for word in [''.join(s) for s in permutations(words,2)]:
    print word

:

hello
helbye
lohel
lobye
byehel
byelo
+1

: , .

Haskell permutations, :

import Data.List
permutations ["hel","lo","bye"] ==
[["hel","lo","bye"],["lo","hel","bye"],["bye","lo","hel"],
 ["lo","bye","hel"],["bye","hel","lo"],["hel","bye","lo"]]

, ,

map concat (permutations ["hel","lo","bye"]) ==
["hellobye","lohelbye","byelohel","lobyehel","byehello","helbyelo"]

(, ) , @Sven, Math.Combinatorics.Graph :

map concat (combinationsOf 2 ["hel","lo","bye"])

, . , " ", , - , , .

0

All Articles