【发布时间】:2018-07-14 20:05:45
【问题描述】:
我想通过使用递归函数没有for循环或while循环来实现代码。
我想实现一个名为 go_through() 的函数,将两个参数作为一个列表(list1)和一个整数(字母),这样如果每个字符串长度的元素都有 大于或等于整数,我替换它使用另一个名为replace_it()的函数
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
所以我对这段代码有疑问 它不允许我停止打印,因为我要打印的是一行
结果看起来像我附上的图片 但是我想在我突出显示的地方停下来并返回它,因为它与我上面写的输出相同。
我该如何解决这个问题?
【问题讨论】:
-
我不知道这是否是主要问题,但
index始终重置为 0,并且以后的增量从未使用过。也许改为将index=0添加到go_through的参数中,并将index放在递归调用中。
标签: python string list recursion