0

I need help with recursion I have a code right here which turns an integer into a list of strings. However, I'm struggling to make it recursive. Here is what I have so far.

def turnList( a ):
   b = str(a)
   c = []

   for digit in b:
    c.append(digit)
   return c
  • 1
    Imagine you already have a recursive version of the function and use it to write your own. Then replace it with your own. – Peter Wood Apr 21 '22 at 20:14
  • 2
    Are you aware of what a recursive function is? You should always start at the base case, the one that doesn't recurse because the input is empty, zero, a single element etc, and then go from there – Iain Shelvington Apr 21 '22 at 20:15
  • And see https://stackoverflow.com/questions/27691547/recursive-function-does-not-return-specified-value to ensure that the recursive step is returned. – Barmar Apr 21 '22 at 20:24

4 Answers4

1

For a recursive function you need a base case, i.e. when we have finished and no longer need to recurse and a generic recursive case

def turnList(a):
    a=str(a)
    if len(a)==1:
        return [a]
    else:
        return [a[0]] + turnList(a[1:])

Our base case is when our recursive function gets a string of length one. And our recursive case returns the first value in its input as a string (in a list) combined with the list of all the 'future' recursive strings.

Stanley
  • 321
  • 2
  • 6
0

Start with a base case, in this case empty list for zero, then define the recursive behavior.

def turnList(a):
    if a == 0:                    # base case
        return []
    a,d = divmod(a,10)            # strip off last digit
    return turnList(a) + [str(d)] # recurse

print(turnList(123))

Output:

['1', '2', '3']
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • i would advise against reassignment of `a` and instead choose a fresh variable, perhaps `next_a` or `smaller_a`. also _"recurse"_ is not a word, you mean to say _"recur"_ – Mulan Apr 22 '22 at 16:57
0

There are multiple ways to do recursion. Here, we adjust bIndex.

b = "hello"

def turnList(c, bIndex):
    if len(b) == bIndex: 
        return c
        
    return turnList(c + [b[bIndex]],bIndex+1)
    
    
print(turnList([],0))
Aaron98990
  • 11
  • 1
-3
global an
an = []
def turnList(a):
    global an
    b=str(a)
    an.append(b[len(b)-1])
    try:
        return turnList(int(b[:len(b)-1]))
    except ValueError as e:
        an.reverse()
        return  an
m = turnList(10)
print(m)

this might be the best i've ever written

alexander
  • 195
  • 1
  • 10