欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

[codewars_python]Sum of Digits / Digital Root

程序员文章站 2023-11-19 16:10:22
Instructions In this kata, you must create a digital root function. A digital root is the recursive sum of all the digits in a number. Given n, take t ......

instructions

in this kata, you must create a digital root function.

a digital root is the recursive sum of all the digits in a number. given n, take the sum of the digits of n. if that value has more than one digit, continue reducing in this way until a single-digit number is produced. this is only applicable to the natural numbers.

here's how it works:

digital_root(16)
=> 1 + 6
=> 7

digital_root(942)
=> 9 + 4 + 2
=> 15 ...
=> 1 + 5
=> 6

digital_root(132189)
=> 1 + 3 + 2 + 1 + 8 + 9
=> 24 ...
=> 2 + 4
=> 6

digital_root(493193)
=> 4 + 9 + 3 + 1 + 9 + 3
=> 29 ...
=> 2 + 9
=> 11 ...
=> 1 + 1
=> 2

my solution:

def digital_root(n):
    lst = [int(x) for x in str(n)]
    result = sum(lst)
    if result < 10:
        return result
    else:
        return digital_root(result)

best solution:

def digital_root(n):
    return n if n < 10 else digital_root(sum(map(int,str(n))))