def digits(n):
res = []
while n > 0:
res.append(n % 10)
n /= 10
return res
I want to rewrite this function so it uses recursion. I’m currently lost as to what to do. Can anyone give me some direction?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here’s a possible solution:
The above solution fixes a bug in your code, you were returning the digits in reverse order. Also notice that
nmust be an integer greater than or equal to zero for producing correct results.Here’s how it works:
digitson a smaller number – namely, the number without the last digit that we just processed.The call to
digits(123)will look like this at each step of the recursion:Now we go up the call stack:
EDIT :
Accepting @thg435’s challenge, here’s a tail-recursive solution: