python - 获取任意长度的所有可能的 str 分区

标签 python arrays string python-3.x

我想找到没有空字符串的字符串的所有可能分区,并且必须包含所有字符(不应包含原始字符串)

例如:

s = '1234'

partitions(s)  # -> [['1', '2', '3', '4'], ['1', '2', '34'], ['1', '23', '4']
               #     ['12', '3', '4'], ['12', '34'], ['1', '234'], ['123', '4']]
               # should not contain ['1234']

编辑:可以按任何顺序

为什么我的问题不是重复的:

我不想要这样的排列:

from itertools import permutations

s = '1234'
permutations(s) # returns ['1', '2', '3', '4'], ['1', '2', '4', '3']...

但是我想把字符串分成很多长度(请看第一段代码)

谢谢!

最佳答案

您可以定义递归(生成器)函数。其思想是:将所有长度的字符串的前缀与剩余字符串的所有分区组合起来。

def partitions(s):
    if len(s) > 0:
        for i in range(1, len(s)+1):
            first, rest = s[:i], s[i:]
            for p in partitions(rest):
                yield [first] + p
    else:
        yield []

partitions("1234") 的结果:

['1', '2', '3', '4']
['1', '2', '34']
['1', '23', '4']
['1', '234']
['12', '3', '4']
['12', '34']
['123', '4']
['1234']

请注意,这确实包含['1234'],但之后可以很容易地对其进行过滤,例如如 print([p for p in partitions("1234") if len(p) > 1]),或者您可以将结果收集到 list 中,然后 pop 最后一个元素。将其直接添加到递归函数中会更加复杂,因为除了顶级调用之外的每个调用都应该返回“完整”分区。

关于python - 获取任意长度的所有可能的 str 分区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52167339/

相关文章:

javascript - JSON 访问循环错误

c - 如何比较 "if"语句中的字符串?

c# - 如何在c#中提取一串文本

python - xpath 按 <br> 标签分割字符串

python - 在 Airflow 上使用 DataprocOperator 的组件网关

java - 初始化对象类型数组

javascript - 在javascript中将字符串拆分为单词

python - 通过索引访问 collections.OrderedDict 中的项目

python - 连续循环并在python中退出

java - 如何在 int 数组中找到两个不同的值?