【发布时间】:2014-06-03 06:18:48
【问题描述】:
我知道如何在 python 中获取纯字符串的排列:
>>> from itertools import permutations
>>> perms = [''.join(p) for p in permutations('stack')]
>>> print perms
...
但是我如何获得'stac'、'stak'、'sack'、'stck'、'stc'、'st' 等的排列?我想要的输出是:
>>> permutations('pet')
['pet', 'pte', 'ept', 'etp', 'tpe', 'tep', 'pe', 'ep', 'p', 'e', 't', 'pt', 'tp', 'et', 'te']
到目前为止我所拥有的:
def permutate(values, size):
return map(lambda p: [values[i] for i in p], permutate_positions(len(values), size))
def permutate_positions(n, size):
if (n==1):
return [[n]]
unique = []
for p in map(lambda perm: perm[:size], [ p[:i-1] + [n-1] + p[i-1:] for p in permutate_positions(n-1, size) for i in range(1, n+1) ]):
if p not in unique:
unique.append(p)
return unique
def perm(word):
all = []
for k in range(1, len(word)+1):
all.append(permutate([' ']+list(word), k))
return all
运行如下:
>>> perm('pet')
[[['t'], ['e'], ['p']], [['t', 'e'], ['e', 't'], ['e', 'p'], ['t', 'p'], ['p', 't'], ['p', 'e'], ['p', 'p']], [['t', 'e', 'p'], ['e', 't', 'p'], ['e', 'p', 't'], ['e', 'p', 'p'], ['t', 'p', 'e'], ['p', 't', 'e'], ['p', 'e', 't'], ['p', 'e', 'p'], ['t', 'p', 'p'], ['p', 't', 'p'], ['p', 'p', 't'], ['p', 'p', 'e']]]
>>>
但是,它有一堆列表,并且具有 ['p', 'p', 't'] 之类的值!
我该怎么做?任何帮助表示赞赏。
【问题讨论】:
-
这个网站上有几个这样的例子。尝试搜索。
-
你的意思是“一个字符串的所有子串的每一个排列”
-
顺便说一句,我们是否应该假设字母是不同的,所以您不需要考虑重复的子字符串? (想想“评估”)。
标签: python string algorithm substring permutation