【问题标题】:How to get every single permutation of all substrings of a string?如何获得字符串的所有子串的每一个排列?
【发布时间】: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


【解决方案1】:

这是使用itertools.permutations 的一种方法:

from itertools import permutations
s = 'pet'
print [''.join(p) for i in range(1, len(s)+1) for p in permutations(s, i)]

输出:

['p', 'e', 't', 'pe', 'pt', 'ep', 'et', 'tp', 'te', 'pet', 'pte', 'ept', 'etp', 'tpe', 'tep']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 2012-05-11
    • 1970-01-01
    • 2014-05-09
    • 2023-02-10
    相关资源
    最近更新 更多