Fetch recursion

I need to write a recursive function getdigits(n)that returns a list of digits in a positive integer n.

Example getdigits(124) => [1,2,4]

So far I have:

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

But for 124 instead [1, 2, 4]I get[[[1], 2], 4]

Working so that in my head it looks like this:

getdigits(124) = [getdigits(12)] + [4]
getdigits(12) = [getdigits(1)] + [2]
get digits(1) = [1]

therefore getdigits(124) = [1] + [2] + [4] = [1, 2, 4]

I believe that something is wrong in the second part, since I do not see anything wrong with the condition, any proposals, without giving out the whole solution?

+3
source share
7 answers

getDigits returns a list, so why do you wrap the list in another (last line)?

+2
source

Your problem is what you return [n]instead of nor use [getDigits(n / 10)]instead getDigits(n / 10).

For example, with your example:

getDigits(124) = [getDigits(12)] + [4] = [getDigits(12), 4]
getDigits(12) = [getDigits(1)] + [2] = [getDigits(1), 2]
getDigits(1) = [1]

:

getDigits(12) = [[1], 2]
getDigits(124) = [[[1], 2], 4]
+1

, . .

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

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

The above will work for an integer n> = 0, note that you do not need to wrap the result getdigits(n/10)inside another list.

+1
source

Your question sounds like homework (recursive requirement), but this can be done with list comprehension

>>> def getdigits(n):
...    return [int(y) for y in str(n)]
... 
>>> getdigits(12345)
[1, 2, 3, 4, 5]
0
source

You can simply use this:

>>> num=124
>>>list(map(int,str(num)))
[1,2,4]
0
source

Using Lambda

(lambda x: [int(a) for a in str(y)])(number)
0
source
def getdigits(n):
    if n<10:
        return [n]
    else:
        return getdigits(n//10)+[n%10]

Your answer is in free circulation. You must use gender separation to make it [1] instead of 1.2

0
source

All Articles