使用递归打印n长度组合而无需重复

时间:2018-12-04 21:05:14

标签: python-3.x recursion combinations

进一步解决此问题:Print n-length combinations from char list using recursion

现在,我必须以另一种方式实现相同的算法:不能重复某些字符。

  

在Python中实现一个函数,该函数接收字符列表和整数n作为参数。该功能必须打印长度为n的所有可能组合,其中每个字符只能显示一次。

所以,由于我是一个初学者并且递归不好,所以我没有想到一个解决问题的优雅方法。

我曾考虑使用与上一个问题相同的代码:

def print_sequences(char_list, n, _accum=[]):
  if len(_accum) == n:
    print(_accum)
  else:
    for c in char_list:
      print_sequences(char_list, n, _accum+[c])

并简单地构建一个新函数(return_without_repetition),该函数接受一个列表并将其遍历,构建一个没有重复的新列表。这样,当我打印列表时,我可以使用以下功能:

if len(_accum) == n:
    print(return_without_repetition(_accum))

但这不是很有效,也不优雅。

也许还有另一种方法可以通过在递归主体中定义新列表来解决它,但我对范围界定和定义列表的合适位置一无所知...

2 个答案:

答案 0 :(得分:1)

如果要重复for列表中的值,则修改链接问题中@ Ajax1234的答案中的逻辑以简单地跳过_accum循环的迭代:

def print_sequences(char_list, n, _accum=[]):
    if len(_accum) == n:
        print(_accum)
    else:
        for c in char_list:
            if c in _accum:
                continue
            print_sequences(char_list, n, _accum+[c])

print_sequences([1, 2, 3, 4], 4)

根据this explanation的组合和排列,我们可以使用4!计算期望的结果数,即24。(同一链接页面解释了为什么4 4 或256,是您上一个问题的答案中预期的结果数)

以上答案将打印出以下24个结果列表:

[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 3, 2, 4]
[1, 3, 4, 2]
[1, 4, 2, 3]
[1, 4, 3, 2]
[2, 1, 3, 4]
[2, 1, 4, 3]
[2, 3, 1, 4]
[2, 3, 4, 1]
[2, 4, 1, 3]
[2, 4, 3, 1]
[3, 1, 2, 4]
[3, 1, 4, 2]
[3, 2, 1, 4]
[3, 2, 4, 1]
[3, 4, 1, 2]
[3, 4, 2, 1]
[4, 1, 2, 3]
[4, 1, 3, 2]
[4, 2, 1, 3]
[4, 2, 3, 1]
[4, 3, 1, 2]
[4, 3, 2, 1]

答案 1 :(得分:0)

此问题实际上是大小为k的所有非重复排列。这是一个易于阅读的版本:

def permutations(items, k):
   def f(path):
      if len(path) == k:
         print(path)
         return
      else:
         for item in items:
             if item not in path:
                 f(path + [item])
      f([])

调用此函数将给出:

[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 3, 2, 4]
[1, 3, 4, 2]
[1, 4, 2, 3]
[1, 4, 3, 2]
[2, 1, 3, 4]
[2, 1, 4, 3]
[2, 3, 1, 4]
[2, 3, 4, 1]
[2, 4, 1, 3]
[2, 4, 3, 1]
[3, 1, 2, 4]
[3, 1, 4, 2]
[3, 2, 1, 4]
[3, 2, 4, 1]
[3, 4, 1, 2]
[3, 4, 2, 1]
[4, 1, 2, 3]
[4, 1, 3, 2]
[4, 2, 1, 3]
[4, 2, 3, 1]
[4, 3, 1, 2]
[4, 3, 2, 1]
相关问题