简体   繁体   English

PYTHON 从递归函数返回一个列表

[英]PYTHON Return a list from a recursive function

I'm coding a program, a part of the program is that I want to create a list with all the substring from a string, using a recursive function.我正在编写一个程序,程序的一部分是我想使用递归函数创建一个包含字符串中所有子字符串的列表。

However, when I return the list, I get nothing.但是,当我返回列表时,我什么也没得到。 The variable substringList has None value.变量 substringList 具有 None 值。

How can I return the list, without losing all the data in it?如何返回列表而不丢失其中的所有数据?

def main(string):
    substringList = []
    substringList = substring(string, substringList)

def substring(string, substringList):#Recursive function to create all the
    length = len(string)             #substrings**strong text**

    if length == 0:
        return substringList

    else:
        substringList.append(string)
        substring(string[1::], substringList)


string = "bananas"
main(string)

You got "None" value because you forgot to use the return command.您得到“无”值是因为您忘记使用return命令。 Also, why are you writing a separate wrapper function to call your recursive function?另外,你为什么要编写一个单独的包装函数来调用你的递归函数? You can do that easily enough in the main program.你可以在主程序中很容易地做到这一点。 You can list the default value of substringList in the calling profile with =[] .您可以使用=[]在调用配置文件中列出 substringList 的默认值。 New code:新代码:

def substring(string, substringList=[]):
    # Recursive function to create all the substrings
    #   of the given string

    if len(string) == 0:
        return substringList

    else:
        substringList.append(string)
        substring(string[1:], substringList)
        return substringList

print substring("bananas")

Now, note that you also haven't written logic to get all of the substrings: you've taken only the ones ending with the final letter.现在,请注意,您还没有编写逻辑来获取所有子字符串:您只获取了以最后一个字母结尾的子字符串。 The way you stated the problem, you need the others as well, such as "nan", "n", etc. I hope that's what you're attacking next.您陈述问题的方式,您还需要其他人,例如“nan”、“n”等。我希望这就是您接下来要攻击的内容。 Note that you might want more recursion: a second call that finds what you get from chopping off the end of this list instead.请注意,您可能需要更多的递归:第二次调用查找您从砍掉此列表末尾获得的信息。 Is that enough of a hint to get you going?这足以让你前进吗?

Is this what you were looking for?这就是你要找的吗?

def main(string):
    substringList = []
    substringList = substring(string, substringList)
    return substringList
def substring(string, substringList):#Recursive function to create all the
    length = len(string)             #substrings**strong text**

    if length == 0:
        return substringList

    else:
        substringList.append(string)
        substring(string[1::], substringList)
        return substringList


string = "bananas"
main(string)

>>>['bananas', 'ananas', 'nanas', 'anas', 'nas', 'as', 's']

Prune's answer above has an issue;上面 Prune 的回答有问题; however, I have yet to earn enough points to comment so here goes.然而,我还没有获得足够的积分来发表评论,所以就这样吧。 If you run the following the result from the second call will include the results of the first call concatenated with the first call.如果您运行以下命令,第二次调用的结果将包括与第一次调用连接的第一次调用的结果。 Ie IE

def substring(string, substringList=[]):
    # Recursive function to create all the substrings
    #   of the given string

    if len(string) == 0:
        return substringList

    else:
        substringList.append(string)
        substring(string[1:], substringList)
        return substringList

print (substring("bananas"))
print (substring("two"))

Results in :结果是 :

['bananas', 'ananas', 'nanas', 'anas', 'nas', 'as', 's'] ['bananas', 'ananas', 'nanas', 'anas', 'nas', 'as', 's', 'two', 'wo', 'o'] ['香蕉','ananas','nanas','anas','nas','as','s'] ['香蕉','ananas','nanas','anas','nas', 'as', 's', 'two', 'wo', 'o']

I think below is a simpler solution to your problem and also fixes the issue pointed out by gordonC.我认为下面是针对您的问题的更简单的解决方案,并且还解决了 gordonC 指出的问题。

def substring(stringList):
    # Recursive function to create all the substrings of the given string
    last_str = stringList[-1]
    if len(last_str) == 1:
        return stringList
    else:
        return substring(stringList + [last_str[1:]])


print(substring(["bananas"]))
print(substring(["two"]))
print(substring(["what"]))

The output is输出是

['bananas', 'ananas', 'nanas', 'anas', 'nas', 'as', 's']
['two', 'wo', 'o']
['what', 'hat', 'at', 't']

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

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