python的遞歸算法學習(1)


遞歸函數
在函數內部,可以調用其他函數。如果一個函數在內部調用自身本身,這個函數就是遞歸函數。
舉個例子,我們來計算階乘 n! = 1 * 2 * 3 * ... * n,用函數 fact(n)表示,可以看出:
fact(n) = n! = 1 * 2 * 3 * ... * (n-1) * n = (n-1)! * n = fact(n-1) * n
所以,fact(n)可以表示為 n * fact(n-1),只有n=1時需要特殊處理。
於是,fact(n)用遞歸的方式寫出來就是:

def fact(n):
if n==1:
  return 1
return n * fact(n - 1)

如果要計算2的n次方,那就是:

def fact(n):
if n==1:
  return 1
return 2 * fact(n - 1)

 

我們可以修改一下代碼,詳細的列出每一步(注意打印出來的內容的順序哦):

def fact(n):
    print("factorial has been called with n = " + str(n))
    if n == 1:
        return 1
    else:
        res = n * fact(n - 1)
        print("intermediate result for ", n, " * fact(", n - 1, "): ", res)
        return res


print(fact(10))

結果是:

C:\Python35\python.exe C:/pylearn/bottlelearn/4.py
factorial has been called with n = 10
factorial has been called with n = 9
factorial has been called with n = 8
factorial has been called with n = 7
factorial has been called with n = 6
factorial has been called with n = 5
factorial has been called with n = 4
factorial has been called with n = 3
factorial has been called with n = 2
factorial has been called with n = 1
intermediate result for  2  * fact( 1 ):  2
intermediate result for  3  * fact( 2 ):  6
intermediate result for  4  * fact( 3 ):  24
intermediate result for  5  * fact( 4 ):  120
intermediate result for  6  * fact( 5 ):  720
intermediate result for  7  * fact( 6 ):  5040
intermediate result for  8  * fact( 7 ):  40320
intermediate result for  9  * fact( 8 ):  362880
intermediate result for  10  * fact( 9 ):  3628800
1814400000

Process finished with exit code 0

進一步思考,如果,我們想實現遞歸的效果,但是,卻不想用到遞歸,在python怎么實現呢:

def fact(n):
    result=1
    for i in range(2,n+1):
        result=result*i
    return result

print(fact(1))
print(fact(2))
print(fact(10))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM