我碰到过这个帖子:How to generate all permutations of a list in PythonPython的排列,包括子
但我需要更多的东西,即所有字符串的排列以及所有的子串的所有排列。我知道这是一个很大的数字,但有可能吗?
我碰到过这个帖子:How to generate all permutations of a list in PythonPython的排列,包括子
但我需要更多的东西,即所有字符串的排列以及所有的子串的所有排列。我知道这是一个很大的数字,但有可能吗?
import itertools
def all_permutations_substrings(a_str):
return (
''.join(item)
for length in xrange(1, len(a_str)+1)
for item in itertools.permutations(a_str, length))
但是请注意,这是真实的排列 - 如,hello
将在它有两个l
小号两次任意子排列,因为l
的将被视为‘独一无二的’。如果你想摆脱它,你可以通过它通过set()
:
all_permutations_no_dupes = set(all_permutations_substrings(a_str))
当你链接状态的问题,itertools.permutations是用于生成列表排列的解决方案。在python中,字符串可以被视为列表,所以itertools.permutations("text")
将工作得很好。对于子字符串,您可以将长度传递给itertools.permutations作为可选的第二个参数。
def permutate_all_substrings(text):
permutations = []
# All possible substring lengths
for length in range(1, len(text)+1):
# All permutations of a given length
for permutation in itertools.permutations(text, length):
# itertools.permutations returns a tuple, so join it back into a string
permutations.append("".join(permutation))
return permutations
或者如果你喜欢一个在线列表内涵
list(itertools.chain.from_iterable([["".join(p) for p in itertools.permutations(text, l)] for l in range(1, len(text)+1)]))
可能重复:http://stackoverflow.com/questions/12273688/algorithm-to-generate-permutations-of-a-list字符串和他们的子字符串 – bdean20