4

これについてstackoverflowを検索しましたが、それを行う方法が見つかりませんでした。おそらく itertools が関係しています。

thisisateststring文字列をn(長さが等しいか等しくないかは関係ありません。両方を含める必要があります)文字列に分割すると、考えられるすべての結果を見つけたいと思います。

たとえば、次のようnにします3

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

3 に答える 3

5

ここで使用できitertools.combinationsます。結果の各文字列を生成するには、2 つの分割ポイントを選択するだけです。

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']
于 2014-04-07T14:53:10.663 に答える
4

結果に空の文字列を含めると、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、任意の string の任意の数のパーティションに対して機能しますs

于 2014-04-07T15:06:06.457 に答える
0

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', '', '']]

small の再帰的ソリューションよりも遅く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
于 2014-05-15T11:47:46.913 に答える