关于python最大递归深度 - 998

LeetCode 233题解析
本文通过一个具体的LeetCode题目,探讨了计算小于等于给定整数中数字1出现次数的问题。给出了一种递归求解的方法,并在实践中遇到了Python最大递归深度限制的问题,最终决定使用迭代方式来解决。

今天LeetCode的时候暴力求解233

  • 问题:

给定一个整数 n,计算所有小于等于 n 的非负数中数字1出现的个数。

例如:

给定 n = 13,

返回 6,因为数字1出现在下数中出现:1,10,11,12,13。

  • 代码:
class Solution:
    def __init__(self):
        self.key = '1'
        self.result = 0

    def countDigitOne(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n < 1:
            return self.result
        self.result += str(n).count(self.key)
        if n > 0:
            self.countDigitOne(n-1)
        return self.result

s = Solution()
print(s.countDigitOne(11221))
  • 错误:

maximum recursion depth exceeded while getting the str of an object

  • 寻找python最大递归深度
class Solution:
    def __init__(self):
        self.key = '1'
        self.result = 0

    def countDigitOne(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n < 1:
            return self.result
        self.result += str(n).count(self.key)
        if n > 0:
            self.countDigitOne(n-1)
        return self.result

s = Solution()
for i in range(0,1000000):
    print(i)
    print(s.countDigitOne(i))

输出 998,然后报错,最大递归深度找到了,还是安心用while吧~

转载于:https://www.cnblogs.com/bincoding/p/8972238.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值