zoukankan      html  css  js  c++  java
  • Python之初识递归

    什么是递归

      在函数中调用函数本身,就是递归,当然不能无限制调用,调用深度为997,想要修改递归深度,用sys模块

    import sys
    sys.setrecursionlimit(100000)  # 修改深度为100000,具体到多少得看及计算机性能

    斐波那契数列

    # 函数形式的斐波那契数列(长度20)
    def func(n):
        if n==1 or n ==2:
            return  1
        return func(n-1)+func(n-2)
    
    ret = func(20)
    print(ret)
    # 堆栈形式的斐波那契数列(长度20)
    l = []
    for i in range(20):
        if i==0 or i==1:
            l.append(1)
        else:
            l.append(l[i-1]+l[i-2])
    print(l[19])

    二分查找算法

    l = [1, 2, 3, 4, 5, 6, 7, 8, 22, 33, 44, 55, 66, 77, 87, 96, 99]
    def func(l,s,start=0,end=None):
        end = len(l) if end is None else end
        mid = (end-start)//2+start
        if start>end:
            return '没有这个元素'
        else:
            if s>l[mid]:
                return func(l,s,start=mid+1,end=end)
            elif s<l[mid]:
                return func(l,s,start=start,end=mid-1)
            elif s==l[mid]:
                return '找到了,在第%s个位置'%mid
    
    ret = func(l,66)
    print(ret)

    三级菜单

    menu = {
        '山西':{
            '太原':{
                '小店区':{},
                '尖草坪区':{}
            },
            '运城':{
                '盐湖区':{},
                '新绛县':{}
            },
            '大同':{}
        },
        '上海':{
            '明珠':{
                '广场':{},
                '雪花啤酒':{}
            },
            '东方':{}
        },
        '山东':{
            '青岛':{
                '青岛啤酒':{},
                '海滩':{}
            },
            '日照':{
                '沙滩':{}
            }
        }
    }
    
    # 递归函数形式的三级菜单
    def threeMenu(menu):
        while True:
            for i in menu.keys():print(i)
            k = input('请选择城市:')
            if k=='b' or k=='q':return k
            elif k in menu.keys() and menu[k]:
                ret = threeMenu(menu[k])
                if ret =='q': return 'q'
            elif (not menu.get(k)) or (not menu[k]):
                continue
    
    threeMenu(menu)
    
    # 堆栈形式的三级菜单
    l = [menu]
    while l:
        for i in l[-1].keys():print(i)
        key = input('请输入:').strip()
        if key in l[-1].keys() and l[-1][key]:l.append(l[-1][key])
        if key=='b':
            l.pop()
        if key=='q':
            break
    三级菜单
  • 相关阅读:
    2dsphere索引
    geoNear查询 near查询的升级版
    geoWithin查询 多边形查询
    [TJOI2013]最长上升子序列
    「bzoj3956: Count」
    「bzoj3687: 简单题」
    「SDOI2008沙拉公主的困惑」
    郑州Day6
    「Luogu-U18201」分析矿洞
    【[COCI2011-2012#5] POPLOCAVANJE】
  • 原文地址:https://www.cnblogs.com/xfdhh/p/9943453.html
Copyright © 2011-2022 走看看