'How do you find the multiplicative persistence of a number? (code not working)

I'm doing a codewars.com test where I've made a function that takes an integer input, and finds it persistence. Persistence is the number of times you have to multiply out each digit in a number until you get a single digit. Ex: 25 -> 2 * 5 = 10 -> 1 * 0 = 0. I've checked my code with print statements and confirmed it did all of the right steps, yet the result is different. Example: I'm given 39 as an argument. My code breaks it down into 3 * 9 which is 27, then 2 * 7, 1 * 4, and finally 4. However, the test I'm using the code on is telling me the result of that number is supposed to be 3. I get slightly different numbers with other arguments as well. I'm assuming there's a step I'm missing at the end but I don't know what I'm supposed to multiply 4, for example, by that'll give me 3 (other than .75 but that doesn't work since .75 isn't a digit of 4)

import numpy

def persistence(n):
   while len(str(n)) > 1:
        #split number into individual digit array
        n = [char for char in str(n)]
        print(n)
        
        #convert types of each array item to int
        for i in range(len(n)):
            n[i] = int(n[i])
        print(n)
        
        #multiply every value in the array
        n = numpy.prod(n)
        print(n)
   return n

I've asked the same question on the codewars site, "returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit." was the response. I can't tell the difference between what I did and what they described is. Help appreciated.



Solution 1:[1]

Just include a counter for the number of times you loop round:

import numpy

def persistence(n):
    times = 0
    while len(str(n)) > 1:
        #split number into individual digit array
        n = [char for char in str(n)]
        print(n)
        
        #convert types of each array item to int
        for i in range(len(n)):
            n[i] = int(n[i])
        print(n)
        
        #multiply every value in the array
        n = numpy.prod(n)
        print(n)
        times += 1
    return times

print(persistence(39))

Output:

['3', '9']
[3, 9]
27
['2', '7']
[2, 7]
14
['1', '4']
[1, 4]
4
3

And 3 is the correct answer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 quamrana