I've written code that solves a problem from codewars.com. My code passes all the tests on the codewars site. It's a simple enough problem to solve naïvely, but I would love to improve the structure.
The prompt for the problem is as follows:
Write a function,
persistence, that takes in a positive parameter
numand returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
persistence(39) => 3 # Because 3*9 = 27, 2*7 = 14, 1*4=4 # and 4 has only one digit.
So my solution follows:
def get_digits(num, digits=): while num > 0: digits.append(num % 10) return get_digits(num / 10, digits) if num == 0: return digits def multiply_all(digits, multiplier=1): while len(digits) > 0: multiplier = multiplier * digits.pop(0) return multiply_all(digits, multiplier) if len(digits) == 0: return multiplier def persistence(num, count=0): while num >= 10: num = multiply_all(get_digits(num)) count += 1 return persistence(num, count) if num < 10: return count
I was thinking I might consolidate these three little recursive functions into one function containing all three... but I'd really like input from more seasoned programmers, so I very much appreciate you taking the time to make any suggestions.