我必须使用递归来解决这个练习。
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/