为了账号安全,请及时绑定邮箱和手机立即绑定

求一个数的数字根

求一个数的数字根

PHP
梦里花落0921 2023-11-09 10:47:34
我尝试实现查找数字的数字根的函数(它是数字中所有数字的递归和。)但由于某种原因,如果函数对自身进行递归调用,它不会返回任何内容import functoolsdef digital_root(n):  r=functools.reduce(lambda x,y:int(x)+int(y),list(str(n)));  if r//10<1:   return r  else:   digital_root(r)
查看完整描述

3 回答

?
倚天杖

TA贡献1828条经验 获得超3个赞

您没有在 else 子句中返回任何值,因此它给出 None


def digital_root(n):

  r=functools.reduce(lambda x,y:int(x)+int(y),list(str(n)));

  if r//10<1:

   return r

  else:

   return digital_root(r)

更具可读性的形式是:


def root(n):

    d_sum = 0

    for i in str(n):

        d_sum += int(i)

    if dsum<10:

        return d_sum

    return root(d_sum)

没有递归:


def root(n):

    while n > 9:

        n = sum(map(int, str(n)))

    return n


查看完整回答
反对 回复 2023-11-09
?
莫回无

TA贡献1865条经验 获得超7个赞

除了缺少 之外return,您还没有查找简化的封闭式算法:

return 9 if (r % 9 == 0) else (r % 9)
# Parentheses are unneeded, but added for readability

数字和的“老派”名称是“casting out nines”。您采用该数字的模基数b-1,其中b是原始数字基数。十进制为 9,十六进制为 15,等等。


查看完整回答
反对 回复 2023-11-09
?
POPMUISE

TA贡献1765条经验 获得超5个赞

我不确切知道您想要实现什么,但我猜您想返回递归调用的结果,因此将示例的最后一行更改为:

   return digital_root(r)


查看完整回答
反对 回复 2023-11-09
  • 3 回答
  • 0 关注
  • 69 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信