zoukankan      html  css  js  c++  java
  • 递归和二分法

    # 递归:在调用一个函数的过程中,又间接或者直接调用了该函数,称之为递归调用
    # 递推和回溯
    # age(5)=age(4)+2
    # age(4)=age(3)+2
    # age(3)=age(2)+2
    # age(2)=age(1)+2
    # age(1)=18

    # age(n)=age(n-1)+2
    # age(1)=18

    # def age(n):
    # if n == 1:
    # return 18
    # return age(n-1)+2
    #
    # res=age(5)
    # print(res) # 26
    # 总结递归的使用:
    # 必须有一个明确的结束条件
    # 每次进入更深一层递归时,问题规模相比上次递归都应有所减少
    # 递归效率不高

    # 二分法
    # l=[1,10,30,66,88,99,100,1000,9999,10000] # 从小到大排列的数字列表
    # def binary_seach(l,num):
    # print(l)
    # mid_index=len(l)//2
    # if num > l[mid_index]:
    # binary_seach(l[mid_index+1:],num)
    # elif num < l[mid_index]:
    # binary_seach(l[0:mid_index], num)
    # else:
    # print('find it')
    #
    # binary_seach(l,99)
    '''
    [1, 10, 30, 66, 88, 99, 100, 1000, 9999, 10000]
    find it
    '''
    # l=[1,10,30,66,88,99,100,1000,9999,10000] # 从小到大排列的数字列表
    # def binary_seach(l,num):
    # print(l)
    # if len(l) == 0:
    # print('not exists')
    # return
    # mid_index=len(l)//2
    # if num > l[mid_index]:
    # binary_seach(l[mid_index+1:],num)
    # elif num < l[mid_index]:
    # binary_seach(l[0:mid_index], num)
    # else:
    # print('find it')
    # binary_seach(l,101)
    '''
    [1, 10, 30, 66, 88, 99, 100, 1000, 9999, 10000]
    [100, 1000, 9999, 10000]
    [100, 1000]
    [100]
    []
    not exists
    '''
    # binary_seach(l,1000)
    '''
    [1, 10, 30, 66, 88, 99, 100, 1000, 9999, 10000]
    [100, 1000, 9999, 10000]
    [100, 1000]
    find it
    '''
  • 相关阅读:
    Yahoo军规
    简单无序列表
    PS切图基本操作
    Web Service 系列 → 智能升级也简单(用Web Services制作升级程序)
    PHP 模板引擎 Smarty
    C# 哈希表(Hashtable)
    ASP.NET 备份与恢复ACCESS数据库
    开源的C#组件 RSS.NET
    Discuz!NT 的URL地址重写(URLRewrite)
    C# SquishIt JavaScript、CSS压缩器
  • 原文地址:https://www.cnblogs.com/0B0S/p/12003133.html
Copyright © 2011-2022 走看看