Day 4:Persistent Bugger

Details:
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.

For example:
 persistence(39) => 3  # Because 3*9 = 27, 2*7 = 14, 1*4=4
                       # and 4 has only one digit.
 persistence(999) => 4 # Because 9*9*9 = 729, 7*2*9 = 126,
                       # 1*2*6 = 12, and finally 1*2 = 2.
 persistence(4) => 0   # Because 4 is already a one-digit number.
My Solution:
def persistence(n):
    times = 0
    if n < 10:
        return times
        
    while True:
        times += 1
        r = 1
        while n > 0:
            r *= n % 10
            n /= 10

        if r < 10:
            return times
        else:
            n = r
Best Practice:
def persistence(n):
    i = 0
    while n>=10:
        n = reduce(lambda x,y:x*y, [int(x) for x in str(n)])
        i += 1
    return i
Tips:
1. 对一组数连续作用某个函数用reduce方法。
2. 把字符串转换成数字list用[int(x) for x in str(n)])
    原文作者:天野
    原文地址: https://segmentfault.com/a/1190000014699345
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞