[英]Getting wrong sum in program to condense a number to a single digit by adding the digits recursively in Python 2.7
[英]Calculate the sum of the digits of a number recursively in Python
我在使用Python的递归函数时遇到麻烦。 该函数的目标是递归计算一个数字的总和。
到目前为止,这就是我所拥有的-我意识到这个版本并不像它那样简洁,但是现在我只是想了解为什么它不能按原样工作:
total = 0 #global variable declaration
def digit_sum(n):
global total #to be able to update the same variable at every level of recursion
total += n % 10 #adding the last digit to the total
n //= 10 #removing the last digit of the number
if n < 10:
total += n
return total
else:
digit_sum(n)
print 'The return value of the function is: ', digit_sum(12345)
print 'The final value stored in total is: ', total
我得到以下输出:
The return value of the function is: None
The final value stored in total is: 15
我的函数在某种程度上起作用,因为存储在全局变量total
的最终值是正确的,但是打印函数输出将返回None
而不是15。
你能帮我理解为什么吗?
谢谢。
有趣的问题和有趣的解决方案! 让我用一个更简单的数字421进行调试。
total
分配值1
, n
变为42
。 else
分支将被执行。 total
的值为3
, n
变为4
。 if
执行了if
分支,则return
值total = 7
。 那么,为什么我们会看到“ None
? 让我们检查一下调用栈:
> digit_sum(n = 421)
> > digit_sum(n = 42) # call to digit_sum from inside digit_sum
> -< 7 # value returned by inner/second call
> None
如您所见,第二个调用返回的值被第一个调用接收,但是第一个调用没有返回第二个调用返回的值 ,因此这就是为什么看到None
的原因。
但是,为什么第一次调用不返回第二次调用返回的值?
由于这一行:
else:
digit_sum(n)
您正在第二次调用该函数,但没有返回其返回值。
希望能帮助到你! :)
问题是您没有在else子句中添加return语句。
添加'return digit_sum(n)'应该可以解决您的问题:
if n < 10:
total += n
return total
else:
return digit_sum(n)
例
当您具有递归函数(我将以n!为例)时,将进行调用,直到达到“基本情况”(n!中为2; n <10时为您)。
让我们看一下阶乘:
def fact(n):
if(n<=2):
return n
else:
return n*fact(n-1)
如果在else子句中没有return语句,则如果您要求fact(4),也将不返回任何内容。
这是带有return语句的“调用”:
返回(4 * fact(3))
返回(4 *(3 * fact(2)))
返回(4 *(3 *(2)))
得出24。
这些是没有的:
(4 *事实上(3))
(4 *(3 *事实(2)))
(4 *(3 *(2)))
这样就进行了演算,但是什么也没有返回。
希望这可以帮助您理解。
注意: 这是解释递归的析因实现。
我的解决方案是
def f(n):
if n/10 == 0:
return n
return n%10 + f(n/10)
输出:
f(12345) = 15
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.