Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion function to find sum of digits in integers using python

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

def main():
    number=int(input("Enter a number :"))
    print(sumdigits(number))
main()
like image 480
rggod Avatar asked Jan 11 '23 20:01

rggod


2 Answers

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)
like image 57
Daniel Avatar answered Jan 28 '23 19:01

Daniel


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
like image 35
Marcellinov Avatar answered Jan 28 '23 19:01

Marcellinov