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)])