問題
正の整数が与えられたとき、その与えられた値の各桁の数字を乗算し、1桁になるまでの回数を返す関数を記述せよ。
例
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): from functools import reduce cnt = 0 while n >= 10 : cnt = cnt + 1 n = reduce( (lambda x,y: int(x) * int(y)), list(str(n)) ) return cnt
0 件のコメント:
コメントを投稿