chaper3. assignment (递归算法)

所谓递归算法就是用上一个算出来的数递推,下一个数字,永远和上一个数字相关。

例如求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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值