前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[codewars_python]Sum

[codewars_python]Sum

作者头像
py3study
发布2020-01-16 11:31:09
5530
发布2020-01-16 11:31:09
举报
文章被收录于专栏:python3
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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
def digital_root(n):
    return n if n < 10 else digital_root(sum(map(int,str(n))))
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/05/24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Instructions
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档