我正在复习一些很好的旧算法,并用 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")
我在这里做的是得到一个由数字组成的字符串;取第一个,将其转换为 int;并再次递归地运行该函数,这样我就可以一次从字符串中取出一位数字并对所有值求和。
理想情况下,输出应显示总数,同时将所有数字相加 (4+5+6+7),尽管在第一次调用递归函数时,该函数会重置总值。
在使用递归函数运行操作时使用全局变量是常见的习惯还是我做错了什么?
最佳答案
您可以像这样简单地编写代码:
def recursive_me(mystring):
if mystring: # recursive case
return int(mystring[0]) + recursive_me(mystring[1:])
else: # base case
return 0
或
def recursive_me(mystring, total = 0):
if mystring: # recursive case
return recursive_me(mystring[1:], total + int(mystring[0]))
else: # base case
return total
虽然这在 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
然后
4
9
15
22
22 # this is the return value; previous output is from `print()`
关于保留变量值的Python递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34519841/