获取距离为1

时间:2016-03-25 22:52:36

标签: python

我对标题感到非常抱歉,但我不知道如何用文字描述我的问题。所以这是一个例子:

假设我们有一个字符串“123”,我的函数应该是产生的:

1 2 3
12 3
1 23

或字符串“1234”:

1 2 3 4
12 3 4
12 34
1 23 4
1 2 34 

我很感激任何帮助或设计方法。

1 个答案:

答案 0 :(得分:0)

这是一个简单的递归方法:在每一步中从字符串中取出1或2个字符,然后递归地将此方法应用于其余部分。

def recurse(left, right, combinations):
    if len(right) > 1:
        recurse(left + ' ' + right[:2], right[2:], combinations)
    if len(right) > 0:
        recurse(left + ' ' + right[:1], right[1:], combinations)
    if len(right) == 0:
        combinations.append(left)
def get_combinations(base):
    combinations = []
    recurse('', base, combinations)
    return combinations
print('\n'.join(print_combinations('abcde')))

这是输出:

ab cd e
ab c de
ab c d e
a bc de
a bc d e
a b cd e
a b c de
a b c d e