日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python的递归算法学习(1)

發(fā)布時間:2025/3/15 python 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python的递归算法学习(1) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

遞歸函數(shù)
在函數(shù)內(nèi)部,可以調(diào)用其他函數(shù)。如果一個函數(shù)在內(nèi)部調(diào)用自身本身,這個函數(shù)就是遞歸函數(shù)。
舉個例子,我們來計(jì)算階乘 n! = 1 * 2 * 3 * ... * n,用函數(shù) 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)

如果要計(jì)算2的n次方,那就是:

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

?

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

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

結(jié)果是:

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 1814400000Process finished with exit code 0

進(jìn)一步思考,如果,我們想實(shí)現(xiàn)遞歸的效果,但是,卻不想用到遞歸,在python怎么實(shí)現(xiàn)呢:

def fact(n):result=1for i in range(2,n+1):result=result*ireturn resultprint(fact(1)) print(fact(2)) print(fact(10))

?

轉(zhuǎn)載于:https://www.cnblogs.com/aomi/p/7047341.html

總結(jié)

以上是生活随笔為你收集整理的python的递归算法学习(1)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。