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

10 投票
8 回答
22062 浏览
提问于 2025-04-16 06:19

我有一串标记,比如:

hel
lo
bye

我想生成所有可能的字符串组合,比如:

hello
lohel
helbye
byehel
lobye
byelo

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

我找到了一些关于使用bash生成排列的内容,但这个方法只是在一行上进行排列。

8 个回答

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
8

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

你的例子可以用Python这样写:

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

如果你想把输出再组合成字符串,可以这样做:

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

如果你对这个函数的具体实现感兴趣,可以查看文档

撰写回答