使用递归从字符列表中打印n个长度的组合 [英] Print n-length combinations from char list using recursion

查看:63
本文介绍了使用递归从字符列表中打印n个长度的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用递归来解决此练习.

I have to solve this exercise using recursion.

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

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.

对我来说,这真是令人难以置信,所有这些思考通常都是递归的.

It's very mind-blowing for me, all this thinking recursively generally.

例如,对于这个问题,我认为已经一个半小时,不知道我在想什么.我不知道如何开始递归思考,我是从哪里开始的?

For example, for this problem, I think already one and a half hour, not knowing what I'm thinking about. I don't know how to start thinking recursively, what am I starting from?

我写了些废话:

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)

请帮助我发展递归意识.

Please help me develop some sense of recursion.

推荐答案

您非常亲密.您需要检查累积的池"列表的长度是否等于参数n,而不是len(char_list) == 1.但是,要创建一个列表以累积组合,请在函数签名中创建一个附加参数:

You are quite close. Instead of len(char_list) == 1, you need to check that the length of your accumulated "pool" list is equal to the parameter n. However, to create a list to accumulate the combinations, create one additional parameter in the signature of the function:

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)

这篇关于使用递归从字符列表中打印n个长度的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆