jakemdaly
jakemdaly

Reputation: 87

Concatenating returned elements to list in a recursive function

This one has been giving me a headache for too long

I am trying to create a list of tuples from a recursion, but I can't quite figure out if how I'm approaching this is going to work or not. Below, foo() and A are aliases for more complicated methods and structures, but I'd like foo() below to return the following:

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8)]

First attempt

When I try adding them together as lists, it nests all the lists.

A = [(num, num) for num in np.arange(9)]
def foo(A):

    if len(A)==1:
        return(A[0])
    else:
        return([A[0]] + [foo(A[1:])])
print(foo(A))

output: [(0, 0), [(1, 1), [(2, 2), [(3, 3), [(4, 4), [(5, 5), [(6, 6), [(7, 7), (8, 8)]]]]]]]]

Second attempt

I can understand why this is wrong, so I tried appending the returned values to the list at the higher level, nothing returns:

A = [(num, num) for num in np.arange(9)]
def foo(A):

    if len(A)==1:
        return(A[0])
    else:
        return([A[0]].append(foo(A[1:])))
print(foo(A))

output: None

Current solution (there's got to be a better way)

def foo(A):

    if len(A)==1:
        return(A[0])
    else:
        return(A[0] + foo(A[1:]))

output: (0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8)

...then:

temp = np.array(foo(A)).reshape(-1,2)
output = [tuple(temp[i, :]) for i in range(np.shape(temp)[0])]
print(output)

which gives the desired output... Can someone give some advice on how to do this correctly using recursion?

Upvotes: 0

Views: 370

Answers (2)

Landon L
Landon L

Reputation: 138

You pretty much had it on your first try. By adding an unpacking and altering your original base case, we can get your desired result.

def foo(A):

    if len(A)==1:
        return([A[0]])
    else:
        return([A[0]] + [*foo(A[1:])])
print(foo(A))

Upvotes: 0

Frank
Frank

Reputation: 1285

I'm not sure what you are asking for since A is already the structure you want. But for your first attempt, you mess up the return type. The first if returns a number, but the second if returns a list. So make sure the first if returns a list, and remove the list conversion in the second if. It should be like this:

import numpy as np

A = [(num, num) for num in np.arange(9)]
def foo(A):

    if len(A)==1:
        return([A[0]])
    else:
        return([A[0]] + foo(A[1:]))
print(foo(A))

Upvotes: 1

Related Questions