[codewars_python]Sum of Digits / Digital Root

Posted icris

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[codewars_python]Sum of Digits / Digital Root相关的知识,希望对你有一定的参考价值。

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))))

 

以上是关于[codewars_python]Sum of Digits / Digital Root的主要内容,如果未能解决你的问题,请参考以下文章

Codeforces 85D. Sum of Medians

D - Sum of Large Numbers

Educational Codeforces Round 108 (Rated for Div. 2)-D. Maximum Sum of Products-题解

Codeforces Round 108(Problem - D Maximum Sum of Products)

[Project Euler 429] Sum of squares of unitary divisors(数论)

Sum of AP series——AP系列之和