我一直在做一些编码练习并遇到了这个我很想理解的解决方案.
问题(我重写了一下,所以不容易搜索):
编写一个接受正参数n的函数,并返回在达到单个数字之前必须将n中的数字相乘的次数.例如:
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.
Run Code Online (Sandbox Code Playgroud)
某人的解决方案:
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
Run Code Online (Sandbox Code Playgroud)
我不明白的是表达式末尾的"+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
Run Code Online (Sandbox Code Playgroud)
所以结果是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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52 次 |
| 最近记录: |