codewars--Sum of Digits

该博客介绍了如何在Codewars上解决'Sum of Digits'问题,即数字根的计算。数字根是通过递归求和所有数字得到的值,直到结果为一位数。文章探讨了使用while而不是if的原因,并解释了map()函数在转换数字到字符串并求和过程中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Sum of Digits / Digital Root

problem describtion:

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 two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.

在这里插入图片描述在这里插入图片描述

Method:

def digital_root(n):
    while n >= 10:
        n=sum(map(int,str(n)))
        digital_root(n)
    return n

If you replace while with if,you can’t get true.Also.I don’t know the reason.

Explanation:

the function of map() :

map(function, iterable, ...)

Using the map() function maps the specified sequence based on the supplied function. The first parameter function, uses the function with each element in the parameter sequence, returning a new list ,containing the values returned by each function with each element.
Here you need to convert the int to string, and then sum() is used directly to sum the string. Using a recursion , calculating a new value determines whether it is a two-digit number.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值