I've been doing some coding exercises and came across this solution which I'd love to understand.
Problem (I re-wrote it a bit so it's not easily searchable):
Write a function that takes in a positive parameter n and returns the number of times one must multiply the digits in n before reaching a single digit. For example:
f(29) => 2 # Because 2*9 = 18, 1*8 = 8,
# and 8 has only one digit.
f(777) => 4 # Because 7*7*7 = 343, 3*4*3 = 36,
# 3*6 = 18, and finally 1*8 = 8.
f(5) => 0 # Because 5 is already a one-digit number.
Someone's solution:
from operator import mul
def f(n):
return 0 if n<=9 else f(reduce(mul, [int(i) for i in str(n)], 1))+1
What I don't understand is how this "+1" at the end of the expression works. Sorry I couldn't title the question more accurately, but I don't know what this is called.
Thanks!
+1? The, 1in thereduce, however, is redundant, as we already know that the list is non-empty.reduce(mul, map(int, str(n)))is enough (and much more elegant IMHO)+1for each "depth" of the recursion, hence you end up with the total "depth", i.e. how often you have to multiply the digits.