Python 是否可以停止此递归函数?
我想通过使用递归函数来实现代码,而不使用for循环或while循环。 我想实现一个名为go_through()的函数,将两个参数作为一个列表(list1)和一个整数(字母),这样,如果每个字符串长度的元素都大于或等于整数,我就使用另一个名为replace_it()的函数来替换它Python 是否可以停止此递归函数?,python,string,list,recursion,Python,String,List,Recursion,我想通过使用递归函数来实现代码,而不使用for循环或while循环。 我想实现一个名为go_through()的函数,将两个参数作为一个列表(list1)和一个整数(字母),这样,如果每个字符串长度的元素都大于或等于整数,我就使用另一个名为replace_it()的函数来替换它 def go_through(list1, letters): get_list = list1[:] num =len(list1) index = 0 if index != num:
def go_through(list1, letters):
get_list = list1[:]
num =len(list1)
index = 0
if index != num:
if len(get_list[0]) >= letters:
get_list += replace_it(get_list[0])
index += 1
print(get_list, 'True')
return go_through(get_list[1:], letters)
else:
get_list += [get_list[0]]
index += 1
print(get_list, 'False')
return go_through(get_list[1:], letters)
else:
print(get_list)
def replace_it(string):
if string == 'pineapple':
return ['peach', 'and', 'pear']
if string== 'delicious':
return ['really', 'gross']
go_through(['pineapple','is','delicious','I', 'want', 'it'],7)
应该看起来像
peach and pear is really gross I want it
因此,我对该代码有一个问题
它不允许我停止打印,因为我只想打印一行
结果将与我所附的图片相似
但是我想在我突出显示的地方停止,并返回它,因为它与我上面写的是相同的输出
如何解决此问题?列表在任何时候都不会减少<
else
块中的code>get\u list+=[get\u list[0]]保持列表大小不变,后面跟着return go\u through(get\u list[1:],字母)
,而中的get\u list+=替换它(get\u list[0])
if
将始终扩展列表
也许你的意思是
else:
# this isn't needed
# get_list += [get_list[0]]
return go_through(get_list[1:], letters)
而且,你似乎在第一点就把列表顺序搞混了
if len(get_list[0]) >= letters:
# this is adding the new list at the end, not replacing the word
# get_list += replace_it(get_list[0])
# you can send the shortened list to the function again,
# and stick the replacement words at the start
return replace_it(get_list[0]) + go_through(get_list[1:], letters)
这个名单在任何时候都没有减少<
else
块中的code>get\u list+=[get\u list[0]]保持列表大小不变,后面跟着return go\u through(get\u list[1:],字母)
,而中的get\u list+=替换它(get\u list[0])
if
将始终扩展列表
也许你的意思是
else:
# this isn't needed
# get_list += [get_list[0]]
return go_through(get_list[1:], letters)
而且,你似乎在第一点就把列表顺序搞混了
if len(get_list[0]) >= letters:
# this is adding the new list at the end, not replacing the word
# get_list += replace_it(get_list[0])
# you can send the shortened list to the function again,
# and stick the replacement words at the start
return replace_it(get_list[0]) + go_through(get_list[1:], letters)
我不知道这是否是主要的问题,但是
索引总是重置为0,并且以后的增量永远不会使用。相反,可以将index=0
添加到的参数中,遍历并将index
放在递归调用中。我不知道这是否是主要问题,但index
总是重置为0,并且从不使用后面的增量。相反,可以将index=0
添加到的参数中,遍历并将index
放在递归调用中。