Keep track of how many times a recursive function was called

后端 未结 9 2131
醉梦人生
醉梦人生 2021-02-02 05:03



        
9条回答
  •  轮回少年
    2021-02-02 05:47

    Here's a Python version that uses a wrapper function to simplify the counter, as has been suggested by slebetman's answer — I write this only because the core idea is very clear in this implementation:

    from functools import reduce
    
    def single_digit(n: int) -> tuple:
        """Take an integer >= 0 and return a tuple of the single-digit product reduction
        and the number of reductions performed."""
    
        def _single_digit(n, i):
            if n <= 9:
                return n, i
            else:
                digits = (int(d) for d in str(n))
                product = reduce(lambda x, y: x * y, digits)
                return _single_digit(product, i + 1)
    
        return _single_digit(n, 0)
    
    >>> single_digit(39)
    (4, 3)
    

提交回复
热议问题