python用递归方式实现最大公约数_关于python最大递归深度 - 998
今天LeetCode的時(shí)候暴力求解233
問題:
給定一個(gè)整數(shù) n,計(jì)算所有小于等于 n 的非負(fù)數(shù)中數(shù)字1出現(xiàn)的個(gè)數(shù)。
例如:
給定 n = 13,
返回 6,因?yàn)閿?shù)字1出現(xiàn)在下數(shù)中出現(xiàn):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))
錯(cuò)誤:
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,然后報(bào)錯(cuò),最大遞歸深度找到了,還是安心用while吧~
總結(jié)
以上是生活随笔為你收集整理的python用递归方式实现最大公约数_关于python最大递归深度 - 998的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: squid 不缓存特定页面_【零基础学云
- 下一篇: websocket python爬虫_p