Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion extracting digits

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

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

So far what I've got is:

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

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

Working that in in my head it goes like:

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

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

I figure there's something wrong in the second part of it as I can't see anything wrong with the condition, any suggestions without giving the entire solution away?

like image 378
Markaj Avatar asked Jul 25 '26 12:07

Markaj


2 Answers

getDigits return a list, so why do you wrap the list into another one (last line)?

like image 52
Vito De Tullio Avatar answered Jul 28 '26 01:07

Vito De Tullio


Your problem is either that you're returning [n] instead of n or using [getDigits(n / 10)] instead of getDigits(n / 10).

For instance, with your example:

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

Therefore it follows:

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