gpt4 book ai didi

python-3.x - 在python3中返回 "list.append"时无限递归

转载 作者:行者123 更新时间:2023-12-03 07:55:42 25 4
gpt4 key购买 nike

我正在编写一个返回单词所有后缀列表的代码。例如,如果我输入

INPUT : "abcdefg" I expect the following output :

OUTPUT : ['abcdefg',·'bcdefg',·'cdefg',·'defg',·'efg',·'fg',·'g', '']

我可以很容易地编写这段代码,使其迭代,但我需要使用递归,所以我编写了以下程序:

def delete_head(my_string):
my_list = list(my_string)
my_list = my_list.pop(0)
return my_list

def list_to_string(my_list):
my_string = "".join(my_list)
return my_string

def suffixes(x):
list_suffixes = [x] #does this makes sense ?

without_head = delete_head(x)
without_head = list_to_string(without_head)

#base cases
if without_head == "" :
return list_suffixes.append("''")

#recursive step
else :
return list_suffixes.append(suffixes(without_head))


def main():
x = input()

print( suffixes(x) )


if __name__ == "__main__":
main()

在上面的代码中,我有两个辅助函数,分别用于:

•通过将字符串转换为列表来删除字符串的第一个元素;•将列表转换为字符串

现在,看看 suffixes 函数,在第一行中,我将单词本身添加到 list_suffixes 中,因为该单词是它自己的后缀,但我担心这会扰乱其他递归调用,因为该值可能会被覆盖。

在基本情况下,如果单词 x 为空,我只想将一个空字符串添加到 list_suffixes 中,否则,我希望下一个后缀为被添加到列表中。

我想我这样做的方式没有多大意义,因为这会产生“无限递归”,所以,如果有人帮助我,我将不胜感激

最佳答案

将程序构建为单独的函数的有用之处之一是您可以单独测试它们,并确保它们按照您的预期运行。

在这种情况下,尝试运行delete_head("hello"),您会发现它返回的不是没有头部的列表,而是头本身。这是因为 pop() 不会返回新列表,它会更改原始列表,并返回它删除的项目。所以你想要这个 - 请注意第二行中的更改:

def delete_head(my_string):
my_list = list(my_string)
my_list.pop(0)
return my_list

实际上有一种更“Pythonic”的方法来使用“切片”删除字符串(或列表)的开头:

def delete_head(my_string)
return my_string[1:]

[1:] 表示“从字符(或项目)1,到字符串(或列表)的末尾”。您还可以指定其他切片,例如 [2:5][:3][-1:](负数表示计数从最后回来)

关于python-3.x - 在python3中返回 "list.append"时无限递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76080910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com