【问题标题】:Return all possible combinations of a string when splitted into n strings拆分为 n 个字符串时返回字符串的所有可能组合
【发布时间】:2014-04-07 14:45:10
【问题描述】:

我为此搜索了 stackoverflow,但找不到解决方法。可能涉及到itertools。

我想找出拆分字符串的所有可能结果,比如将字符串thisisateststring 转换为n(长度相等或不等,都应该包含)字符串。

例如让n3

[["thisisat", "eststrin", "g"], ["th", "isisates", "tstring"], ............]

【问题讨论】:

  • 是否允许空子字符串?
  • 所以从数学上讲,您正在寻找长度(字符串)的所有不同可能的大小和 n,然后排列它们?
  • @C.B.:从他的问题中,我了解到他只想要将字符串拆分为 n 个子字符串的所有可能方法(因此,当您连接 s1 + s2 + s3 时,您会得到原始字符串)。跨度>
  • SvenMarnach,是的,他们是被允许的。 C.B.,是的,你可以这样说,但保罗的说法听起来更简洁,但可能与你所说的相同。保罗,完全正确。

标签: python string list chunks


【解决方案1】:

您可以在此处使用itertools.combinations。您只需要选择两个分割点来生成每个结果字符串:

from itertools import combinations
s = "thisisateststring"
pools = range(1, len(s))
res = [[s[:p], s[p:q], s[q:]] for p, q in combinations(pools, 2)]
print res[0]
print res[-1]

输出:

['t', 'h', 'isisateststring']
['thisisateststri', 'n', 'g']

【讨论】:

  • 这不包括空字符串,扩展为空字符串很尴尬。
【解决方案2】:

使用itertools.combinations() 在结果中包含空字符串会很尴尬。编写自己的递归版本可能是最简单的:

def partitions(s, k):
    if not k:
        yield [s]
        return
    for i in range(len(s) + 1):
        for tail in partitions(s[i:], k - 1):
            yield [s[:i]] + tail

这将适用于任何数量的k 任何字符串s 的所需分区。

【讨论】:

  • 我知道这是一个愚蠢(而且非常简单)的问题,但是有没有办法让它返回一个列表,因为当我执行它返回的代码时:
  • list(partitions("abcde", 3))一样称呼它。
【解决方案3】:

下面是根据code by Raymond Hettinger 将序列划分为 n 个组的方法:

import itertools as IT

def partition_into_n(iterable, n, chain=IT.chain, map=map):
    """
    Based on http://code.activestate.com/recipes/576795/ (Raymond Hettinger)
    Modified to include empty partitions, and restricted to partitions of length n
    """
    s = iterable if hasattr(iterable, '__getslice__') else tuple(iterable)
    m = len(s)
    first, middle, last = [0], range(m + 1), [m]
    getslice = s.__getslice__
    return (map(getslice, chain(first, div), chain(div, last))
            for div in IT.combinations_with_replacement(middle, n - 1))

In [149]: list(partition_into_n(s, 3))
Out[149]: 
[['', '', 'thisisateststring'],
 ['', 't', 'hisisateststring'],
 ['', 'th', 'isisateststring'],
 ['', 'thi', 'sisateststring'],
 ...
 ['thisisateststrin', '', 'g'],
 ['thisisateststrin', 'g', ''],
 ['thisisateststring', '', '']]

它比小n的递归解决方案要慢,

def partitions_recursive(s, n):
    if not n>1:
        yield [s]
        return
    for i in range(len(s) + 1):
        for tail in partitions_recursive(s[i:], n - 1):
            yield [s[:i]] + tail

s = "thisisateststring"
In [150]: %timeit list(partition_into_n(s, 3))
1000 loops, best of 3: 354 µs per loop

In [151]: %timeit list(partitions_recursive(s, 3))
10000 loops, best of 3: 180 µs per loop

但正如您所料,大型n 会更快(随着递归深度的增加):

In [152]: %timeit list(partition_into_n(s, 10))
1 loops, best of 3: 9.2 s per loop

In [153]: %timeit list(partitions_recursive(s, 10))
1 loops, best of 3: 10.2 s per loop

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    相关资源
    最近更新 更多