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.
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
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
1. 對(duì)一組數(shù)連續(xù)作用某個(gè)函數(shù)用reduce方法。 2. 把字符串轉(zhuǎn)換成數(shù)字list用[int(x) for x in str(n)])
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/41658.html