保留变量值的Python递归函数

5 python recursion

我正在刷新一些好的旧算法,并用python做,因为我现在经常使用它.

运行递归函数时我遇到了一个问题; 每次递归函数调用自身时变量都会重置:

def recursive_me(mystring):
    chars = len(mystring)
    if chars is 0:
        print("Done")
    else:
        first = int(str[0])
        total = + first
        print(total)
        recursive_me(mystring[1:])

recursive_me("4567")
Run Code Online (Sandbox Code Playgroud)

我在这里做的是得到一个由数字组成的字符串; 取第一个,将其转换为int; 并再次递归运行该函数,因此我可以从字符串中取一个数字并将所有值相加.

理想情况下,输出应显示总数,同时它会添加所有数字(4 + 5 + 6 + 7),但是当第一次调用递归函数时,该函数会重置总值.

在使用递归函数运行操作时是否习惯使用全局变量,或者我做错了什么?

use*_*lpa 8

您可以像这样简单地编码:

def recursive_me(mystring):
    if mystring: # recursive case
        return int(mystring[0]) + recursive_me(mystring[1:])
    else:        # base case
        return 0
Run Code Online (Sandbox Code Playgroud)

要么

def recursive_me(mystring, total = 0):
    if mystring: # recursive case
        return recursive_me(mystring[1:], total + int(mystring[0]))
    else:        # base case
        return total
Run Code Online (Sandbox Code Playgroud)

虽然这对Python没有多大帮助,因为它没有实现尾调用优化.

如果要查看中间值,请更改第二个版本,如下所示:

def recursive_me(mystring, total = 0):
    if mystring: # recursive case
        newtotal = total + int(mystring[0])
        print(newtotal)
        return recursive_me(mystring[1:], newtotal)
    else:        # base case
        return total
Run Code Online (Sandbox Code Playgroud)

然后

4
9
15
22
22 # this is the return value; previous output is from `print()`
Run Code Online (Sandbox Code Playgroud)

  • @ Untitled123迭代解决方案没有任何调用堆栈,因为它不会调用自身.当然,在Python中编写这样的代码是不自然的,但是在其他语言中,例如Scheme,其中第二种解决方案是迭代的常规方法. (2认同)