使用python查找整数中数字总和的递归函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20130902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:38:56  来源:igfitidea点击:

Recursion function to find sum of digits in integers using python

pythonfunctionrecursion

提问by rggod

def sumdigits(number):
  if number==0:
    return 0
  if number!=0:
    return (number%10) + (number//10)

this is the function that I have. However its only give the proper sum of 2 digit numbers. How can i get the sum of any number. Also would my function count as recursion

这是我的功能。然而,它只给出 2 位数字的正确总和。我怎样才能得到任何数字的总和。我的函数也会算作递归吗

def main():
    number=int(input("Enter a number :"))
    print(sumdigits(number))
main()

回答by Alexander L. Belikoff

You don't make a recursive step (calling sumdigits()inside)!

您没有进行递归步骤(调用sumdigits()内部)!

回答by MondKin

No, it is not recursive as you are not calling your function from inside your function.

不,它不是递归的,因为您不是从函数内部调用函数。

Try:

尝试:

def sumdigits(number):
  if number == 0:
    return 0
  else:
    return (number%10) + sumdigits(number//10)

回答by MondKin

For a function to be recursive, it must call itself within itself. Furthermore, since your current one does not do this, it is not recursive.

对于递归的函数,它必须在自身内部调用自身。此外,由于您当前的不这样做,因此它不是递归的。

Here is a simple recursive function that does what you want:

这是一个简单的递归函数,可以执行您想要的操作:

>>> def sumdigits(n):
...     return n and n%10 + sumdigits(n//10)
...
>>> sumdigits(457)
16
>>> sumdigits(45)
9
>>> sumdigits(1234)
10
>>>

回答by Marcellinov

Recursion is a way of programming or coding a problem, in which a function calls itself one or more times in its body.

递归是一种对问题进行编程或编码的方法,其中函数在其主体中一次或多次调用自身。

Usually, it is returning the return value of this function call. If a function definition fulfils the condition of recursion, we call this function a recursive function.

通常,它返回此函数调用的返回值。如果一个函数定义满足递归条件,我们称这个函数为递归函数。

A recursive function has to terminate to be used in a program. Usually, it terminates, if with every recursive call the solution of the problem is downsized and moves towards a base case. A base case is a case, where the problem can be solved without further recursion. (a recursion can lead to an infinite loop, if the base case is not met in the calls). For this problem, the "base case" is:

递归函数必须终止才能在程序中使用。通常,如果每次递归调用问题的解决方案都缩小并朝着基本情况移动,它就会终止。基本情况是这样一种情况,即无需进一步递归即可解决问题。(如果调用中未满足基本情况,递归可能导致无限循环)。对于这个问题,“基本情况”是:

if number == 0:
    return 0

A simple recursive function for sum all the digits of a number is:

对一个数的所有数字求和的简单递归函数是:

def sum_digits(number):
    """ Return the sum of digits of a number.
        number: non-negative integer
    """

    # Base Case
    if number == 0:
        return 0
    else:
        # Mod (%) by 10 gives you the rightmost digit (227 % 10 == 7), 
        # while doing integer division by 10 removes the rightmost 
        # digit (227 // 10 is 22)

        return (number % 10) + sumdigits(number // 10)

If we run the code we have:

如果我们运行代码,我们有:

>>>print sum_digits(57) # (5 + 7) = 12 
12
>>>print sum_digits(5728) # (5 + 7 + 2 + 8) = 22
22

回答by HandyFrank

I believe this is what you are looking for:

我相信这就是你要找的:

def sum_digits(n):
    if n < 10:
        return n
    else:
        all_but_last, last = n // 10, n % 10
        return sum_digits(all_but_last) + last

回答by Hymantrader

While recursion is a clever way to go, I'd generally stay away from it for performance and logic reasons (it can get complex pretty quick). I know it's not the answer you are looking for but I'd personally stick to something like this or some kind of loop:

虽然递归是一种聪明的方法,但出于性能和逻辑原因,我通常会远离它(它可能很快变得复杂)。我知道这不是你正在寻找的答案,但我个人会坚持这样的事情或某种循环:

def sumdigits(number):
    return sum(map(int, str(number)))

Good luck!

祝你好运!