RECURSIVE函数将总和输入的数字 [英] RECURSIVE function that will sum digits of input

查看:172
本文介绍了RECURSIVE函数将总和输入的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图写一段代码来总结一个数字的数字。另外我还要补充一点,我希望程序继续总结数字,直到总和只有1位数。例如,如果你从1969开始,它应该首先加1 + 9 + 6 + 9得到25.因为值25不止一个数字,它应该重复操作获得7作为最终答案。

只是想知道我该如何解决这个问题,并且可能使其递归。这是我到目前为止

  def sum_digits3(n):
r = 0
while n:
r,n = r + n%10,n // 10
return r


 >>> def foo(n):
n = str(n)
if len(n)== 1:
return int(n)
return foo(sum(int(c) for c in n))

>>> foo(1969)
7
>>>






  def foo(n):
n = str(n)
如果len(n)== 1:
返回int(n)
返回foo(sum(int(c)for c in n))


Trying to write a piece of code that will sum the digits of a number. Also I should add that I want the program to keep summing the digits until the sum is only 1 digit.

For example, if you start with 1969, it should first add 1+9+6+9 to get 25. Since the value 25 has more than a single digit, it should repeat the operation to obtain 7 as a final answer.

Was just wondering how I could pull this off and possibly make it recursive as well. This is what I have so far

def sum_digits3(n):
     r = 0
     while n:
         r, n = r + n % 10, n // 10
     return r   

解决方案

Convert back and forth between strings and ints, make use of sum().

>>> def foo(n):
    n = str(n)
    if len(n) == 1:
        return int(n)
    return foo(sum(int(c) for c in n))

>>> foo(1969)
7
>>> 


def foo(n):
    n = str(n)
    if len(n) == 1:
        return int(n)
    return foo(sum(int(c) for c in n))

这篇关于RECURSIVE函数将总和输入的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆