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?
getDigits return a list, so why do you wrap the list into another one (last line)?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With