I need to get the digital root of a positive number using Python, so far my algorithms don't work.
In theory, the digits of each number should be added until there is only 1 digit left in the number.
For example:
127 = 1+2+7 = 10
1+0 = 1
Therefore the digital root of 127 would be 1
.
This was my last algorithm:
def getDigitalRoot(num):
return num if num==9 else num%9
But it doesn't work well since if I put for example 99 it returns 0 and it would have to be 9.
Using a recursive function, you can do something like this:
What it does first is calculate the sum of all the digits by converting the integer to a string:
Then each digit is converted back to an integer to be added with the function
sum
:It is verified that the result is a one-digit number (
suma < 10
) and recursion is used if it is greater than one digit to finally obtain the digital root.Update
Using @Darkhogg's suggestion, I've changed the list comprehension to a generator, which only affects the sum line. Changed from:
A:
I found a pretty elegant way to get what I was looking for:
In this way I solved the problem I had when putting 99 for example, before it returned me 0 and now it gives me 9 correctly.
The problem can be solved without recursion and by using the reduce builtin and the fact that in Python strings are iterable just like lists.
Result
The digital root of 127 is 1 and not 10 (appears in the question):
The digital root of n is equal to the remainder of dividing n by 9 dr(n)= n mod 9
this is demonstrated in
https://www.todoexpertos.com/preguntas/63pngi45njkno6f3/cual-es-el-procedimiento-que-permite-expresar-la-raiz-digital-por-medio-de-la-funcion-parte-entera-piso
The only drawback is that if n is a multiple of 9, n mod 9 = 0 and we want 9 to come out. This is solved with the function
dr(n) = (n - 1) mod 9 + 1
In Python this would be def getDigitalRoot(num): return (num-1)%9 +1