Digital Root without loops Python

后端 未结 6 856
无人及你
无人及你 2021-01-25 07:58
def digit_sum(n):
    \'\'\'(int)->number
    Returns the sum of all the digits in the given integer, n\'\'\'
    if n<10:
        return n
    return n%10 + digit         


        
相关标签:
6条回答
  • 2021-01-25 08:23
    def droot(a):
        while a>=10:
             b =int(a/10) #other digit(s)
             c =a-(b*10)  #the rightmost digit
             a =b+c #add together
        return a
    

    I have not seen this solution anywhere, so I thought it would be nice to share, i discovered it myself! Just 1 looping structure.

    0 讨论(0)
  • 2021-01-25 08:31

    Wikipedia lists a simple O(1) formula for the digital root:

    def digit_root(n): 
        return (n - 1) % 9 + 1
    

    This does not take into account an input less than 1, so you can modify as follows, with the assumption that the input is a whole number:

    def digit_root(n): 
        return (n - 1) % 9 + 1 if n else 0
    

    Examples:

    >>> digit_root(1)
    1
    >>> digit_root(11)
    2
    >>> digit_root(235)
    1
    
    0 讨论(0)
  • 2021-01-25 08:31

    please try the following code:

    def dgtl_rt(n):
       return n%9 or n and 9
    print(dgtl_rt(123))
    
    0 讨论(0)
  • 2021-01-25 08:33
    {def MDR(n):
        '''
        this function returns multiplicative digital root.
        '''
        count, mdr = 0, n 
        while mdr > 9:
            m, digitsMul = mdr, 1
            while m:
                m, md = divmod(m, 10)
                digitsMul *= md
            mdr = digitsMul
            count += 1
        return count, mdr}
    
    0 讨论(0)
  • 2021-01-25 08:38

    Try this:

    def num(n) :   
         sum = 0   #provided sum as 0
         for i in str(n): 
             a = int(n) % 10    #taken variable a 
             sum  = sum + a   #put the sum.
             n = n/10
         print(sum)    
         if sum < 10:    
             print(str(sum) + "=this is a digital root")
         else:
             num(sum)
    
    0 讨论(0)
  • 2021-01-25 08:44

    So the idea is that you have to use recursion for the last one as well? In that case, this should do the job:

    def digital_root(n):
        if n < 10:
            return n
        return digital_root(digit_sum(n))
    
    0 讨论(0)
提交回复
热议问题