gpt4 book ai didi

python - 递归表达式解释? (Python)

转载 作者:行者123 更新时间:2023-11-28 20:59:29 25 4
gpt4 key购买 nike

我一直在做一些编码练习并遇到了这个我很想了解的解决方案。

问题(我重写了一点所以不容易搜索到):

Write a function that takes in a positive parameter n and returns the number of times one must multiply the digits in n before reaching a single digit. For example:

 f(29) => 2  # Because 2*9 = 18, 1*8 = 8, 
# and 8 has only one digit.

f(777) => 4 # Because 7*7*7 = 343, 3*4*3 = 36,
# 3*6 = 18, and finally 1*8 = 8.

f(5) => 0 # Because 5 is already a one-digit number.

有人的解决方案:

from operator import mul
def f(n):
return 0 if n<=9 else f(reduce(mul, [int(i) for i in str(n)], 1))+1

我不明白表达式末尾的“+1”是如何工作的。抱歉,我无法更准确地为问题命名,但我不知道这叫什么。

谢谢!

最佳答案

计数加1,乘以调用函数

让 f(777) => 4,

It will add one and call f - 343
count = 1
It will add one and call f - 36
count = 2
It will add one and call f -18
count = 3
It will add one and call f - 8

所以结果是4

函数调用看起来像

f(7777)
=1+f(343)
=1+(1+f(36))
=1+(1+(1+f(18)))
=1+(1+(1+(1+f(8))))
=1+1+1+1+0 = 4

关于python - 递归表达式解释? (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49488373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com