Home > Back-end >  Return a list recursively
Return a list recursively

Time:04-22

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

CodePudding user response:

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.

CodePudding user response:

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']

CodePudding user response:

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))

CodePudding user response:

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

  • Related