【问题标题】:Ranking permutations recursively in python在python中递归排列排列
【发布时间】:2017-01-23 14:21:22
【问题描述】:

我怎样才能格式化这个函数,使它递归地工作?如果可能的话,我想更深层次,而不是只到 5 级。

permutations 是一个具有不同排列的列表,这些单独的排列也可以有排列等。我想根据我在 get_permutations 中所做的一些计算对它们进行排名,并返回新的排列顺序。查看它的一个好方法可能是列表列表列表的列表列表。首先,我想更改第一级的顺序,而不是更深一步等。但最终我根据这些排列而不是排列本身(如果重要的话)返回字符串,其中 res1...res5 是字符串。我不够聪明,无法让它递归工作,即使我知道它应该是可能的......有什么想法吗?

permutations, res1 = get_permutations(str, 1)

for p2 in permutations:
    permutations_2, res2 = get_permutations(p2,2)

        for p3 in permutations_2:
            permutations_3, res3 = get_permutations(p3,3)

            for p4 in permutations_3:
                permutations_4, res4 = get_permutations(p4, 4)

                for p5 in permutations_4:
                    permutations_5, res5 = get_permutations(p5,5)

                res4 += res5
            res3 += res4    
        res2 += res3    
    res1 += res2

return res1

编辑:这将返回单个(最佳)排列。这就是结果的目的。所以不是答案中提到的可能排列的列表。例如。如果我们有一个列表列表,如果首先根据所有子信息对列表进行排序,然后根据前一个排序和所有子信息对多个列表列表进行排序,然后根据前两个排序对列表列表进行排序.

【问题讨论】:

标签: python recursion permutation


【解决方案1】:

一个递归生成器函数,它产生与原始字符串相关的预期顺序的排列:

def get_permutations(a):
    if len(a) <= 1:
        yield a
    else:
        for i in xrange(len(a)):
            for p in get_permutations(a[:i]+a[i+1:]):
                yield ''.join([a[i]])+p

>>> a = '123'
>>> list(get_permutations(a))
['123', '132', '213', '231', '312', '321']

这里的递归原理:

  1. 基本情况:长度字符串(0, 1)只有一个排列:它们自己。

  2. 递归:对于字符串中的每个字母,将其删除并将其添加到字符串余数的每个排列之前。

【讨论】:

    【解决方案2】:

    下面的示例,此方法通过以递归方式重复次数嵌套 for 循环来工作。然后我们累积子解决方案的结果,附加到结果列表中:

    result = []
    def permutations(alphabet, repeat, total = ''):
        if repeat >= 1:
            for i in alphabet:
                # Add the subsolutions.     
                permutations(alphabet, repeat - 1, total + i)  
    
        else:
            result.append(total)
        return result
    

    样本输出:

    permutations('ab', 3) ->
    $ ['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']
    permutations('ab', 3) ->
    $ ['aaa', 'aab', 'aac', 'aba', 'abb', 'abc', 'aca', 'acb', 'acc', 'baa',
      'bab', 'bac', 'bba', 'bbb', 'bbc', 'bca', 'bcb', 'bcc', 'caa', 'cab', 
      'cac', 'cba', 'cbb', 'cbc', 'cca', 'ccb', 'ccc']
    permutations('ab', 1) ->
    $ ['a', 'b']
    

    来源:a previous answer of mine.

    【讨论】:

      猜你喜欢
      • 2012-10-18
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 2011-06-18
      • 2011-07-23
      • 1970-01-01
      • 1970-01-01
      • 2020-02-06
      相关资源
      最近更新 更多