Recursion extracting digits
Solution 1
getDigits return a list, so why do you wrap the list into another one (last line)?
Solution 2
The same question has been answered before, see the link for more details.
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, notice that you don't have to wrap the result of getdigits(n/10)
inside another list.
Markaj
Updated on June 26, 2022Comments
-
Markaj almost 2 years
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?