从令牌列表生成所有可能的字符串

时间:2010-10-30 16:21:41

标签: python bash language-agnostic

我有一个令牌列表,例如:

hel
lo
bye

我希望生成这些字符串的所有可能组合,例如:

hello
lohel
helbye
byehel
lobye
byelo

语言不重要,有什么建议吗?

我找到Generating permutations using bash,但这会在一行上进行排列。

8 个答案:

答案 0 :(得分:18)

您的示例可以用Python编写

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

将输出再次组合到字符串:

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

如果您对此功能的实际实施感兴趣,请查看documentation

答案 1 :(得分:6)

itertools.permutations可以为您做到这一点。

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

答案 2 :(得分:3)

鉴于其他语言可以接受:

#!/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 :(得分:2)

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

答案 4 :(得分:1)

使用itertools轻松实现python。

以下是令牌排列示例:

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)

答案 5 :(得分:1)

Python也有permutations。 :)

答案 6 :(得分: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

答案 7 :(得分:0)

更新:我看到我不够明确。

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

这在某些方面与您的示例数据匹配,但与其他方面不匹配。我可以继续推测你想要标题所说的“所有可能的字符串”,或者双标记子集的所有排列,或者你有什么,但是因为你已经接受了答案,所以推测它是毫无意义的。 / p>