python - 使用递归从字符列表打印 n 长度组合

标签 python python-3.x list recursion combinations

我必须使用递归来解决这个练习。

Implement a function in Python which recieves as parameters list of characters and an integer n. The function has to print all the possible combinations in the length of n, where every character can be shown more than one time.

这对我来说非常令人兴奋,所有这些一般都是递归思考的。

比如这个问题,我想了一个半小时,不知道自己在想什么。我不知道如何开始递归思考,我从什么开始?

我写了一些废话:

def print_sequences(char_list, n):
if len(char_list) == 1:
    print(char_list[1])
else:
    sub_str = ""
    for c in char_list:
        print_sequences(list(sub_str + c), n)

请帮助我培养一些递归意识。

最佳答案

你们已经很接近了。您需要检查累积的“池”列表的长度是否等于参数n,而不是len(char_list) == 1。但是,要创建一个列表来累积组合,请在函数签名中创建一个附加参数:

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])


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

输出:

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

编辑:实现 _accum 作为默认列表:

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])

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

关于python - 使用递归从字符列表打印 n 长度组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53561500/

相关文章:

python - SQLAlchemy 在事务中空闲

python - 优雅的结构化文本文件解析

python - 如何使用pycharm在远程服务器上的远程docker上设置安全连接

Python - 检查元组列表中的项目组合

c# - 无法将 foreach 更改为 LINQ 语法

python - Django : When is sessionid cookie set ? [默认可用吗? ]

Python - 读取表情符号 Unicode 字符

python-3.x - Pandas 总计数高于阈值

python - 将列表解压为字符串,将它们拆分并从那里创建字典

java - 将文本文件中的数据解析为 HashMap