簡體   English   中英

在Python中遞歸計算一個數字的總和

[英]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進行調試。

  1. 第一次調用時, total分配值1n變為42 else分支將被執行。
  2. 在第二次調用時, total的值為3n變為4 if執行了if分支,則returntotal = 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語句的“調用”:

    1. 返回(4 * fact(3))

    2. 返回(4 *(3 * fact(2)))

    3. 返回(4 *(3 *(2)))

得出24。

  • 這些是沒有的:

    1. (4 *事實上(3))

    2. (4 *(3 *事實(2)))

    3. (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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM