Что я делаю неверно? (Задача с Codewars 6 kyu)
Условия задачи:
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) # returns 3, because 3*9=27, 2*7=14, 1*4=4
# and 4 has only one digit
persistence(999) # returns 4, because 9*9*9=729, 7*2*9=126,
# 1*2*6=12, and finally 1*2=2
persistence(4) # returns 0, because 4 is already a one-digit number
Мое решение данной задачи (у меня в IDE все условия выполняются):
class Counter(object):
counter = 0
def persistence(n):
s = str(n)
if len(s) > 1:
Counter.counter += 1
num = int(s[0])
for x in range(1, len(s)):
num *= int(s[x])
return persistence(num)
else:
return Counter.counter
test.it("Basic tests")
test.assert_equals(persistence(39), 3)
test.assert_equals(persistence(4), 0)
test.assert_equals(persistence(25), 2)
test.assert_equals(persistence(999), 4)
Ответы (1 шт):
Автор решения: Neuro
→ Ссылка
Можем работать с самим числом, без преобразования в строку. Это можно сделать с помощью целочисленного деления на 10, а также брать остаток. Когда целочисленное деление на 10 дает 0, значит в числе 1 символ и может возвращать.
def R(number):
if number//10==0:
return 0
res = 1
while(True):
res*=number%10
number//=10
if number == 0:
break
return R(res)+1
