python - 如何计算递归深度而不在 Python 中传递计数参数?
问题描述
编写一个函数,持久性,它接受一个正参数n
并返回其乘法持久性,这是您必须将数字相乘n
直到达到单个数字的次数。
例如:
我已经尝试过这个有效的代码,但游戏的规则是我不能传递 2 个参数。所以我必须消除这个counter
论点。
def persistence(n,counter): #recursion
n = list(str(n))
product = 1
for i in n:
product *= int(i)
if product < 10:
return counter+1
else:
counter +=1
return persistence(product,counter)
persistence(39) # returns 3, because 3*9=27, 2*7=14, 1*4=4
# and 4 has only one digit
解决方案
如果您想保持算法相同,可以使用默认参数:
def persistence(n, counter=0):
product = 1
for i in str(n):
product *= int(i)
if product < 10:
return counter + 1
return persistence(product, counter + 1)
print(persistence(39))
话虽如此,正如@TomKarzes 指出的那样,根本不需要counter
参数(或递归)——将结果传回调用堆栈而不是向上。任何给定的调用都不需要来自先前调用的任何信息,除了n
自身的当前状态来确定持久性。
def persistence(n):
product = 1
for i in str(n):
product *= int(i)
if product < 10:
return 1
return persistence(product) + 1
print(persistence(39))
推荐阅读
- mongodb - 聚合查询返回空数组
- python - Mac 上的 Python 版本帮助
- scala - Scala 自定义类型类
- performance - 如何编写代码来测量我的 android 手机的 FLOPS
- azure - 仅从 Azure 存储 [Azure-Blob][REST] 中的 Blob 列表获取特定元数据
- ruby-on-rails - Rails 服务器无法在 docker 容器中启动
- javascript - React Rodal 不适合模式窗口内的文本
- java - Java:线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 3 at javaapplication9.Tictactoe.setPlay
- javascript - 图像处理 Discord.js:没有这样的文件或字典
- javascript - THree.js:从正交相机缩放时如何保持精灵文本大小不变