递归是神马
>>> 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)
递归球阶乘
写一个求阶乘的函数
正整数阶乘从1乘以2乘以3乘以4一直乘到所要求的数。
例如所给的数是5,则阶乘式是1*2*3*4*5,得到的积是120,所以120就是5的阶乘。
非递归版本的实现
>>> def factorial(n):
... result = n
... for i in range(1,n):
... result *= i
... return result
...
>>> print('%d 的阶乘是: %d' % (5,factorial(5)))
5 的阶乘是: 120
递归实现
>>> def recursion(x):
... if x == 1:
... return x
... else:
... return x * recursion(x-1)
...
>>> recursion(5)
120
>>> recursion(6)
720
递归效率低,方法调用
递归使用不当,死循环
斐波那契(Fibonacci) Leonardo Fibonacci
迭代实现
>>> def fabnacii(n):
... n1 = 1
... n2 = 1
... n3 = 1
... if(n < 1):
... print('输入出错')
... return -1
... while((n - 2) > 0):
... n3 = n1 + n2
... n1 = n2
... n2 = n3
... n -= 1
... return n3
...
>>> fabnacii(10)
55
递归实现
>>> def fab(n):
... if n < 1:
... print('输入出错')
... 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个盘子从x移动到y上
... print(x, '-->', z)#将最底下的最后一个盘子从x移动到z上
... hanoi(n-1, y,x,z)#将y上的n-1个盘子移动到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