How to rewrite this function as a recursive function?

def digits(n):
    res = []
    while n > 0:
        res.append(n % 10)
        n /= 10
    return res

I want to rewrite this function so that it uses recursion. I have now lost what to do. Can someone give me some direction?

0
source share
4 answers

Here a solution is possible:

def digits(n):
    if n < 10:
        return [n]
    return digits(n/10) + [n%10]

digits(123)
> [1, 2, 3]

The above solution corrects the error in your code, you return the numbers in the reverse order. Also note that it nmust be an integer greater than or equal to zero to get the correct results.

Here's how it works:

  • If the number is less than 10, return the list with the number, since you no longer need to process the numbers
  • 9, , digits , , .

digits(123) :

digits(123) = digits(123/10) + [3]
digits(12)  = digits(12/10)  + [2]
digits(1)   = [1]

:

[1]
[1] + [2]
[1, 2] + [3]
[1, 2, 3]

EDIT:

@thg435, :

def digits(n):
    def loop(i, acc):
        if i < 10:
            return [i] + acc
        return loop(i/10, [i%10] + acc)
    return loop(n, [])
+2

, :

1) - ,

2) - ,

, - while, - while. .

+6

, , , . , , n > 0 ( while, while). ( ) , , while, . , n/10.

, :

def digits(n):

, n 0, , , :

    if n <= 0:
        return []

Now, in the recursive case, you want to add n% 10 to the list and call your function again, only you want to call it with another n, changed just like in your while loop:

    else:
        return [n%10]+digits(n/10)

So, if you follow this, for each recursive case you get a list containing n% 10, then it will add the result of a new call, which will be either (n / 10)% 10 or an empty list, For example, running this function with n = 100 will look like this:

newlist = digits(100)
newlist = [100%10]+digits(100/10)
newlist = [100%10]+([10%10] + digits(10/10))
newlist = [100%10]+([10%10] + ([1%10] + digits(10/10)))
newlist = [100%10]+([10%10] + ([1%10] + ([])))
newlist = [0,0,1]

Nested parsers are used to show how function digits will be overwritten by the built-in ones.

0
source
def digits(n):
    res = []
    res.append(n%10)
    n /= 10
    if n != 0:
        return res + digits(n)
    else:
        return res
0
source

All Articles