Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取距离为1的两个元素的所有组合_Python - Fatal编程技术网

Python 获取距离为1的两个元素的所有组合

Python 获取距离为1的两个元素的所有组合,python,Python,关于这个题目我真的很抱歉,但我不知道如何用语言来描述我的问题。下面是一个例子: 假设我们有一个字符串“123”,我的函数应该是: 1 2 3 12 3 1 23 或对于字符串“1234”: 我将非常感谢任何帮助或设计配方。这里有一个简单的递归方法:在每一步从字符串中提取1到2个字符,然后递归地将此方法应用于剩余部分 def recurse(left, right, combinations): if len(right) > 1: recurse(left + '

关于这个题目我真的很抱歉,但我不知道如何用语言来描述我的问题。下面是一个例子:

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

1 2 3
12 3
1 23
或对于字符串“1234”:


我将非常感谢任何帮助或设计配方。

这里有一个简单的递归方法:在每一步从字符串中提取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

下面是一个简单的递归方法:在每一步从字符串中提取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

小心-长度为n的字符串的输出数为n+1次斐波那契数,从f0=0开始计数。这很快变得完全无法管理。你确定你需要这样做吗?无论你想通过这样做来解决什么问题,你都可以采取一种更有效的方法。这听起来像是一项适合你的工作。如果向您提供了翻译
130
的方法数和翻译
1306
的方法数,您如何使用该信息快速确定翻译
13065
的方法数?一旦你明白了这一点,你就可以根据所涉及的思想来制定一个算法。注意——长度为n的字符串的输出数是n+1次斐波那契数,从f0=0开始计算。这很快变得完全无法管理。你确定你需要这样做吗?无论你想通过这样做来解决什么问题,你都可以采取一种更有效的方法。这听起来像是一项适合你的工作。如果向您提供了翻译
130
的方法数和翻译
1306
的方法数,您如何使用该信息快速确定翻译
13065
的方法数?一旦你明白了这一点,你就可以根据所涉及的想法来制定一个算法。