【问题标题】:Is it possible to stop this recursive function?是否可以停止此递归函数?
【发布时间】: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


【解决方案1】:

该列表在任何时候都不会减少。 else 块中的get_list += [get_list[0]] 后跟return go_through(get_list[1:], letters) 时保持列表大小相同,而if 中的get_list += replace_it(get_list[0]) 将始终扩展列表。

也许你的意思是像

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)

【讨论】:

    猜你喜欢
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 2013-03-30
    • 1970-01-01
    相关资源
    最近更新 更多