這是一種避免遞歸的方法。它通過列出對的起始索引來指紋所有可能的分區。如果m是輸入字符串然後ķ雙所有這樣的指紋可以通過
- 構建的查找所有
itertools.combination
S的ķ出米長度 - ķ然後
- 加入1到第二位置,2到第三3到第四等
代碼:
m = 'abcdef'
fp = [[l+i for i, l in enumerate(c)] for k in range(len(m) // 2 + 1) for c in it.combinations(range(len(m)-k), k)]
fp
# [[], [0], [1], [2], [3], [4], [0, 2], [0, 3], [0, 4], [1, 3], [1, 4], [2, 4], [0, 2, 4]]
[list(m)] + [list(m[:f[0]]) + sum([[m[i:i+2]] + list(m[i+2:j]) for i, j in zip(f,f[1:] + [len(m)])], []) for f in fp[1:]]
# [['a', 'b', 'c', 'd', 'e', 'f'], ['ab', 'c', 'd', 'e', 'f'], ['a', 'bc', 'd', 'e', 'f'],
['a', 'b', 'cd', 'e', 'f'], ['a', 'b', 'c', 'de', 'f'], ['a', 'b', 'c', 'd', 'ef'],
['ab', 'cd', 'e', 'f'], ['ab', 'c', 'de', 'f'], ['ab', 'c', 'd', 'ef'], ['a', 'bc', 'de', 'f'],
['a', 'bc', 'd', 'ef'], ['a', 'b', 'cd', 'ef'], ['ab', 'cd', 'ef']]
@Julien:這是不是所有的組合 - - 單打和雙打。但是,鏈接將有助於獲得解決方案。 – Prune
您是否嘗試過創建一個接受字符串的函數,迭代sting的長度,並返回一個包含每個char和每對的列表?這應該是幾行代碼,您可以將其提供給itertools.combinations。 – SuperTetelman
我認爲你可以使用受限制的分區來做些什麼https://en.m.wikipedia.org/wiki/Partition_(number_theory)#Restricted_partitions –