美文网首页我爱编程
python中设定递归深度

python中设定递归深度

作者: 代码小工蚁 | 来源:发表于2018-05-28 15:01 被阅读47次

    python中设定递归深度

    递归调用中如果出现无限递归或过多的堆栈层级(占用大量的内存)会导致堆栈溢出。
    在默认的情况下,python中执行以下程序就会报错。

    def fact(n):
        if n == 1:
            return 1
        else:
            return n*fact(n-1)
            
    print(fact(999))
    

    出错提示信息:

    RecursionError: maximum recursion depth exceeded in comparison

    (递归错误:比较中超出最大递归深度)

    在确定不是无限递归的情况下,可以使用sys.setrecursionlimit(n)来增加递归深度:
    sys.getrecursionlimit() 获取当前的最大递归深度(默认是1000)
    sys.setrecursionlimit(n) 设定最大递归深度

    在上面程序的开始处加入:

    import sys
    
    sys.setrecursionlimit(10000)
    
    

    再运行程序就不会有错误,能得到运行结果。

    相关文章

      网友评论

        本文标题:python中设定递归深度

        本文链接:https://www.haomeiwen.com/subject/fargjftx.html