[codewars_python]Sum of Digits / Digital Root

2019-04-11 10:31:58来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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

 


原文链接:https://www.cnblogs.com/icris/p/10659236.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Python简介

下一篇:python第三次作业——叶耀宗