Python 递归函数返回None
我编写的代码返回一个列表,其中包含字母表alpha上给定长度的所有字符串,没有特定顺序。例如:Python 递归函数返回None,python,Python,我编写的代码返回一个列表,其中包含字母表alpha上给定长度的所有字符串,没有特定顺序。例如: all_strings({0, 1}, 3)) 应该回来 ['000', '001', '010', '011', '100', '101', '110', '111'] 这两个功能: def all_strings(alpha, length): alpha_list = [] # store in a list the elements in the set alpha for
all_strings({0, 1}, 3))
应该回来
['000', '001', '010', '011', '100', '101', '110', '111']
这两个功能:
def all_strings(alpha, length):
alpha_list = [] # store in a list the elements in the set alpha
for symbol in alpha:
alpha_list.append(symbol)
if length == 1:
return alpha_list
else:
return recurs_func(alpha, length, alpha_list)
def recurs_func(alpha, length, update_list):
new_list = [] # list to store new strings
for j in alpha:
for k in update_list:
new_list.append(j+k)
if length == 2: # done creating strings of desired length
return new_list
else:
recurs_func(alpha, length-1, new_list)
代码运行良好,除非我选择长度>=3,在这种情况下,不会返回任何值,并且不知道如何解决这个问题 您忘记了最后一行的退货。应该是:
return recurs_func(alpha, length-1, new_list)
在
recurse\u func
中,如果length
不是2,则进行递归调用,但不返回任何内容