所谓递归算法就是用上一个算出来的数递推,下一个数字,永远和上一个数字相关。
例如求2!,用fact(n)来实现
fact(n) = n! = 1 * 2 * 3 * ... * (n-1) * n = (n-1)! * n = fact(n-1) * n
def fact(n):
if n=1:
renturn 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("factrorial has been called with n =",n,"*fact(",n-1,"):",res)
return res
print(fact(5))
#结果
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
factrorial has been called with n = 2 *fact( 1 ): 2
factrorial has been called with n = 3 *fact( 2 ): 6
factrorial has been called with n = 4 *fact( 3 ): 24
factrorial has been called with n = 5 *fact( 4 ): 120
120
Process finished with exit code 0
进一步思考,如果,我们想实现递归的效果,但是,却不想用到递归,在python怎么实现呢:
def fact(n):
result=1
for i in range(2,n+1):
result=result*i
return result
def fact(n):
if n==1 :
return 1
if n==2:
return 2
else:
res=fact(n-1)+fact(n-2)
return res
print(fact(10))
2.实验内容
费波拉契数列:就是n10=res(9)+10
def fact(n):
if n==1 :
return 1
if n==2:
return 2
else:
res=fact(n-1)+fact(n-2)
return res
print(fact(10))
注意:在else里面的返回值里面,真正的值是fact(),不存在res(),只是一个中间代码。和VB不同
or
a=1
b=2
while b<100:
print(b)
a,b=b,a+b
注意:不要胡缩进
list的方法
list= []
for i in range(10):
if i==0 or i==1:
list.append(1)
else:
list.append(list[i-1]+list[i-2])
print(list)