递归表达式解释? (蟒蛇)

时间:2018-03-26 09:42:18

标签: python recursion

我一直在做一些编码练习,并遇到了我喜欢理解的解决方案。

问题(我重写了一下,因此不容易搜索):

  

编写一个带有正参数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.

某人的解决方案:

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

我不明白的是这个&#34; + 1&#34;在表达结束时工作。对不起,我无法更准确地标题,但我不知道这是什么。

谢谢!

2 个答案:

答案 0 :(得分:5)

它为计数和调用函数加上1乘以值

让我们拿f(777)=&gt; 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

答案 1 :(得分:1)

首先考虑迭代方法,您可以获得一些见解:

def f(n):
    for i in count():
        if n <= 9:
            return i
        digits = [int(i) for i in str(n)]
        n = reduce(mul, digits, 1)

并找到相应的递归:

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

请注意,不是使用i参数,而是可以递增返回值:

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

然后可以采用功能齐全的方法去除影响:

digits = lambda n: map(int, str(n))
product = lambda xs: reduce(mul, xs, 1)
digit_product = lambda n: product(digits(n))
f = lambda n: 0 if n <= 9 else 1 + f(digit_product(n))