繁体   English   中英

是否可以停止此递归函数?

[英]Is it possible to stop this recursive function?

我想使用不带for循环或while循环的递归函数来实现代码

我想实现一个名为go_through()的函数,并采用两个参数作为list(list1)和一个integer(letters),以便如果每个字符串长度的元素都大于或等于integer ,我 使用另一个函数 替换叫做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

所以我对此代码有问题,因为我要打印的是一行,所以不允许我停止打印

结果看起来像是我附加的图片,但是我想在突出显示的地方停止并返回它,因为它与我上面写的输出相同。

在此处输入图片说明

我该如何解决这个问题?

这个清单在任何时候都没有减少。 get_list += [get_list[0]]else块保持列表,其后当相同尺寸return go_through(get_list[1:], letters) ,而get_list += replace_it(get_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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM