求一个数的数字根

我尝试实现查找数字的数字根的函数(它是数字中所有数字的递归和。)但由于某种原因,如果函数对自身进行递归调用,它不会返回任何内容


import functools

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


梦里花落0921
浏览 71回答 3
3回答

倚天杖

您没有在 else 子句中返回任何值,因此它给出 Nonedef digital_root(n):&nbsp; r=functools.reduce(lambda x,y:int(x)+int(y),list(str(n)));&nbsp; if r//10<1:&nbsp; &nbsp;return r&nbsp; else:&nbsp; &nbsp;return digital_root(r)更具可读性的形式是:def root(n):&nbsp; &nbsp; d_sum = 0&nbsp; &nbsp; for i in str(n):&nbsp; &nbsp; &nbsp; &nbsp; d_sum += int(i)&nbsp; &nbsp; if dsum<10:&nbsp; &nbsp; &nbsp; &nbsp; return d_sum&nbsp; &nbsp; return root(d_sum)没有递归:def root(n):&nbsp; &nbsp; while n > 9:&nbsp; &nbsp; &nbsp; &nbsp; n = sum(map(int, str(n)))&nbsp; &nbsp; return n

莫回无

除了缺少 之外return,您还没有查找简化的封闭式算法:return&nbsp;9&nbsp;if&nbsp;(r&nbsp;%&nbsp;9&nbsp;==&nbsp;0)&nbsp;else&nbsp;(r&nbsp;%&nbsp;9) #&nbsp;Parentheses&nbsp;are&nbsp;unneeded,&nbsp;but&nbsp;added&nbsp;for&nbsp;readability数字和的“老派”名称是“casting out nines”。您采用该数字的模基数b-1,其中b是原始数字基数。十进制为 9,十六进制为 15,等等。

POPMUISE

我不确切知道您想要实现什么,但我猜您想返回递归调用的结果,因此将示例的最后一行更改为:&nbsp;&nbsp;&nbsp;return&nbsp;digital_root(r)
打开App,查看更多内容
随时随地看视频慕课网APP