python字符串子集的所有组合

前端之家收集整理的这篇文章主要介绍了python字符串子集的所有组合前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要字符串子集的所有组合.另外,长度为1的子集之后只能是长度> 1的子集.例如对于字符串4824,结果应该是:
  1. [ [4,824],[4,82,4],[48,24],[482,[4824] ]

到目前为止,我设法检索所有可能的子集:

  1. length = len(number)
  2. ss = []
  3. for i in xrange(length):
  4. for j in xrange(i,length):
  5. ss.append(number[i:j + 1])

这给了我:

  1. ['4','48','482','4824','8','82','824','2','24','4']

但我现在不知道如何将它们结合起来.

解决方法

首先,编写一个函数生成字符串的所有分区:
  1. def partitions(s):
  2. if s:
  3. for i in range(1,len(s) + 1):
  4. for p in partitions(s[i:]):
  5. yield [s[:i]] + p
  6. else:
  7. yield []

这将迭代所有可能的第一个段(一个字符,两个字符等),并将这些段与字符串的相应剩余部分的所有分区组合在一起.

  1. >>> list(partitions("4824"))
  2. [['4','4'],['4','24'],'824'],['48',['482',['4824']]

现在,您可以只过滤那些符合您条件的条件,即那些没有两个连续长度为1的子串的条件.

  1. >>> [p for p in partitions("4824") if not any(len(x) == len(y) == 1 for x,y in zip(p,p[1:]))]
  2. [['4',['4824']]

这里,zip(p,p [1:])是迭代所有连续项对的常用方法.

更新:实际上,将约束直接合并到分区函数中也不是那么难.只需跟踪最后一段并相应地设置最小长度.

  1. def partitions(s,minLength=1):
  2. if len(s) >= minLength:
  3. for i in range(minLength,len(s) + 1):
  4. for p in partitions(s[i:],1 if i > 1 else 2):
  5. yield [s[:i]] + p
  6. elif not s:
  7. yield []

演示:

  1. >>> print list(partitions("4824"))
  2. [['4',['4824']]

猜你在找的Python相关文章