Search code examples
pythonrecursion

How to count recursion depth without passing a count argument in Python?


Write a function, persistence, that takes in a positive parameter n and returns its multiplicative persistence, which is the number of times you must multiply the digits in n until you reach a single digit.

For example:

I have tried this code which works but the game's rule is that I cannot pass 2 arguments. So I have to eliminate the counter argument.

def persistence(n,counter): #recursion

    n = list(str(n))
    product = 1

    for i in n:
        product *= int(i)

    if product < 10:
        return counter+1

    else:
        counter +=1
        return persistence(product,counter)
persistence(39) # returns 3, because 3*9=27, 2*7=14, 1*4=4
                 # and 4 has only one digit

Solution

  • You could use a default argument if you wanted to keep your algorithm the same:

    def persistence(n, counter=0):
        product = 1
    
        for i in str(n):
            product *= int(i)
    
        if product < 10:
            return counter + 1
    
        return persistence(product, counter + 1)
    
    print(persistence(39))
    

    Having said that, as @TomKarzes points out, there's no need for the counter argument at all (or recursion for that matter)--pass the result back up the call stack rather than down. Any given call doesn't need any information from previous calls other than the current state of n itself to determine persistence.

    def persistence(n):
        product = 1
    
        for i in str(n):
            product *= int(i)
    
        if product < 10:
            return 1
    
        return persistence(product) + 1
    
    print(persistence(39))