以下Python代码完美无缺,但如果我在第9行取消注释print
,我会得到奇怪的输出。更糟糕的是,如果我评论第8行并取消注释第9行,我会收到一条错误消息“TypeError:'NoneType'对象不可迭代”。
有人能揭开神秘面纱吗?到底是怎么回事?
def all_perms(the_string):
all_perm=[]
if len(the_string)==1:
return the_string
else:
for char in the_string:
for word in all_perms(the_string.replace(char,'')):
all_perm.append(char+word) # line 8
# print(char+word) # line 9
return all_perm
the_string="hey"
all_perms(the_string)
答案 0 :(得分:0)
该函数应该返回一个排列列表。但是在递归的基本情况下,您只需返回the_string
而不是列表。它应该返回一个元素的列表:
if len(the_string) == 1:
return [the_string]
如果要在函数中打印字符串,请添加一个区分顶级调用和递归调用的参数。
def all_perms(the_string, recursing = False):
all_perm=[]
if len(the_string)==1:
return [the_string]
else:
for char in the_string:
for word in all_perms(the_string.replace(char,''), recursing=True):
all_perm.append(char+word)
if !recursing:
print(char+word)
return all_perm
the_string="hey"
all_perms(the_string)
答案 1 :(得分:0)
试试这个
def all_perms(the_string):
all_perm=['']
if len(the_string)==1:
all_perm.append(the_string)
return all_perm
else:
for char in the_string:
for word in all_perms(the_string.replace(char,'')):
all_perm.append(char+word)
return all_perm
the_string="hey"
print(sorted(all_perms(the_string)[1:],key=len))