简体   繁体   中英

How to modify this Python function to use recursion

I have a simple function that breaks a number such as 54 and returns the sum of those two number (ie 9 ). I am also studying recursion, I am wondering if the code below meets the criteria. Why? or Why Not?. If not how can I solve this simple problem using the recursion paradigm?

def sumnum(n):
    n = str(n)
    a = []
    for i in n:
        a.append(i) 
    sum(int(n) for n in a)
sumnum(54)
9

The code you have used is not recursion. Recursion has two main characteristics: the base case, and the recursion.

Now, lets break down you your problem:

Base case:

Say we have the number smaller than 10. Then we would return the number. Let's keep it as our base case.

Recursion:

If we had a number ...xyz ( x , y and z as digits), we would take the last digit, plus the last digit of the number left, until we have a number smaller than 10.

Code:

def sumnum (n):
    if n < 10:
        return n
    return n % 10 + sumnum(n // 10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM