![](/img/trans.png)
[英]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.