2024-06-26 00:27:54 发布
网友
我有一个令牌列表,比如:
hel lo bye
我想生成这些字符串的所有可能组合,比如:
hello lohel helbye byehel lobye byelo
语言不重要,有什么建议吗?
我找到了Generating permutations using bash,但这使排列在一行上。
考虑到其他语言是可以接受的:
#!/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
您的示例可以用Python编写为
from itertools import combinations print list(combinations(["hel", "lo", "bye"], 2))
要再次将输出合并到字符串:
print ["".join(a) for a in combinations(["hel", "lo", "bye"], 2)]
如果您对这个函数的实际实现感兴趣,请查看documentation。
^{}可以帮你。
>>> l = ['hel', 'lo', 'bye'] >>> list(itertools.permutations(l, 2)) [('hel', 'lo'), ('hel', 'bye'), ('lo', 'hel'), ('lo', 'bye'), ('bye', 'hel'), ('bye', 'lo')]
或者如果需要组合,可以使用^{}。
>>> l = ['hel', 'lo', 'bye'] >>> list(itertools.combinations(l, 2)) [('hel', 'lo'), ('hel', 'bye'), ('lo', 'bye')]
考虑到其他语言是可以接受的:
您的示例可以用Python编写为
要再次将输出合并到字符串:
如果您对这个函数的实际实现感兴趣,请查看documentation。
^{} 可以帮你。
或者如果需要组合,可以使用^{} 。
相关问题 更多 >
编程相关推荐