Sum of Digits / Digital Root — codewars
How I Solved the Codewars ‘Sum of Digits / Digital Root’ Challenge
This problem is currently rated as a 6 kyu (ratings on codewars range from 8 (easiest) to 1 (hardest)) problem on codewars, this is its description :
“Digital root is the recursive sum of all the digits in a number.
Given
n
, take the sum of the digits ofn
. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.”
My thoughts before solving:
When I read the description, I thought of solving it using recursion. (recursion is when a function calls itself in python)
My python solution:
digital_root = lambda n: digital_root(sum(map(int,str(n)))) if n > 9 else n
We start with an if statement that checks if “n: int” is a singular digit by checking if it is greater than 9. If it is, the function calls itself.
str(n)
We convert the integer to a string so we can split it into a list. ( str() is used for converting different data types to strings. It can also be used for changing the encoding of a string.)
map(int,str(n))
Then we wrap it with map() so we can convert the string to an integer list. (with wrap you can change what data type you want with the first argument. Here I made it an integer list using int as our first argument.)
sum(map(int,str(n)))
After we supply it to sum() so we can add all the digits together. (sum is used for getting the sum/ adding all values together in a list.) We recursively call the function with that as our ‘n’ argument.
In conclusion
That is how I solved ‘Sum Of Digits / Digital Root’ on codewars, hopefully this helps you improve!
— 0xsweat 7/14/2024
My socials :