I encounter a strange problem:
a digital root function is something looks like this:
digital_root(493193)
=> 4 + 9 + 3 + 1 + 9 + 3
=> 29 ...
=> 2 + 9
=> 11 ...
=> 1 + 1
=> 2
and my answer is:
def digital_root(n):
k = 10
while k > 9:
k = reduce(lambda x,y: int(x)+int(y), list(str(n)))
return k
I set k to 10 so that it will directly go in to the loop. But the online judge says it costs too much time.
and I try another solution:
def digital_root(n):
while n > 9:
n = reduce(lambda x,y: int(x)+int(y), list(str(n)))
return n
then the problem solved. I can figure out what's the difference between these two codes
By the way, I use the codewars online judge.