5
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()

8 Answers 8

6

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)
Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

return (number % 10) + sum_digits(number // 10) # Typo
1

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

Comments

0

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

Comments

0

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

Comments

0

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!

Comments

0

I was working on this recently hope it will help someone in future

def digit(n):
    p=0
    for i in str(n):
        p += int(i)
    return p

def superDigit(n):  
    if n==0:
       return 0
    return digit(digit(digit(digit(n))))

Comments

0

Here's a solution to summing a series of integer digits that uses ternary operators with recursion and some parameter checking that only happens the first time through the function. Some python coders may consider this less pythonic (using ternary expressions), however, it demonstrates how to use recursion, answering the original question, while introducing ternary operators to combine a few multi-line if/else statements into simple math.

Note that:

  • int * True = int, whereas int * False = 0

  • float * True = Float, whereas float * False = 0

  • "Text" * True = "Text", but "Text" * False = ""; but also

  • "Text" * 0 = "", whereas "Text" * 3 = "TextTextText"

  • "Text" * float = Error; whereas "Text" * int = Error

  • The one-line if/else statement reads as follows: Expression_if_True if Condition_to_Check else Expression_if_False

     def digitSum2(n = 0, first = True):
         if first:
             first = False
             if type(n) != int or n < 0:
                 return "Only positive integers accepted."
         return (n * (n < 10) + (n % 10 + digitSum2(n // 10, first)) * (n >= 10)) if (n > 0) else 0
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.