python--14 递归
遞歸是神馬
?
>>> def recursion():
... recursion()
...
>>> recursion()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in recursion
File "<stdin>", line 2, in recursion
File "<stdin>", line 2, in recursion
[Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded
>>> import sys
>>> sys.setrecursionlimit(1000000)
?
遞歸球階乘
寫一個(gè)求階乘的函數(shù)
正整數(shù)階乘從1乘以2乘以3乘以4一直乘到所要求的數(shù)。
例如所給的數(shù)是5,則階乘式是1*2*3*4*5,得到的積是120,所以120就是5的階乘。
非遞歸版本的實(shí)現(xiàn)
>>> def factorial(n):
... result = n
... for i in range(1,n):
... result *= i
... return result
...
>>> print('%d 的階乘是: %d' % (5,factorial(5)))
5 的階乘是: 120
遞歸實(shí)現(xiàn)
>>> def recursion(x):
... if x == 1:
... return x
... else:
... return x * recursion(x-1)
...
>>> recursion(5)
120
>>> recursion(6)
720
遞歸效率低,方法調(diào)用
遞歸使用不當(dāng),死循環(huán)
斐波那契(Fibonacci) ?Leonardo Fibonacci
?? 迭代實(shí)現(xiàn)
>>> def fabnacii(n):
... n1 = 1
... n2 = 1
... n3 = 1
... if(n < ?1):
... print('輸入出錯(cuò)')
... return -1
... while((n - 2) > 0):
... n3 = n1 + n2
... n1 = n2
... n2 = n3
... n -= 1
... return n3
...
>>> fabnacii(10)
55?
遞歸實(shí)現(xiàn)
>>> def fab(n):
... if n < 1:
... print('輸入出錯(cuò)')
... if n==1 or n==2:
... return 1
... else:
... return fab(n-1) +fab(n-2)
...
>>> fab(10)
55
分治思想
遞歸 -- 漢諾塔
>>> def hanoi(n,x,y,z):
... if n == 1:
... print(x, '-->', z)
... else:
... hanoi(n-1,x,z,y)#將n-1個(gè)盤子從x移動(dòng)到y(tǒng)上
... print(x, '-->', z)#將最底下的最后一個(gè)盤子從x移動(dòng)到z上
... hanoi(n-1, y,x,z)#將y上的n-1個(gè)盤子移動(dòng)到z上
...
>>> hanoi(4,'x','y','z')
x --> y
x --> z
y --> z
x --> y
z --> x
z --> y
x --> y
x --> z
y --> z
y --> x
z --> x
y --> z
x --> y
x --> z
y?--> z
轉(zhuǎn)載于:https://www.cnblogs.com/fengjunjie-w/p/7491736.html
總結(jié)
以上是生活随笔為你收集整理的python--14 递归的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信历史消息java_微信聊天机器人[过
- 下一篇: 记录请求的耗时(拦截器、过滤器、aspe