-1

I have this code that is progressively generating a larger multidimensional array recursively.

def lex(stop,n = 2,array = [[0,0],[1,-1]]):
    if n == 2:
        if stop == 2:
            return array
        else:
            return lex(stop,n+1,array)

    else:
        newArray = []
        for x in range(n):
            for y in range(len(array)):
                newArray.append(array[y][:])

        for x in range(len(newArray)):
            pos = x // factorial(n-1)
            newArray[x].insert(pos,-pos)
            for y in range(pos):
                if y < x: newArray[x][y] += 1

        if n == stop:
            print(newArray)
            return newArray
        else:
            lex(stop,n+1,newArray)

The strange part is at the end in the if n == stop block. print(newArray prints the correct array but the return statement doesn't seem to work. Any attempt at printing the result just shows None.

Is there something functionally wrong with how I'm returning the array?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
robjtede
  • 736
  • 5
  • 16

1 Answers1

2

The return newArray is working fine; you forgot a return statement for the recursive call in the else branch:

if n == stop:
    print(newArray)
    return newArray
else:
    # don't ignore this recursive call
    return lex(stop,n+1,newArray)

You want to avoid using a mutable default argument to your function; use a sentinel like None instead:

def lex(stop, n=2, array=None):
    if array is None:
        array = [[0, 0], [1, -1]]

Cleaning up the code a little more:

def lex(stop, n=2, array=None):
    if array is None:
        array = [[0, 0], [1, -1]]

    if n == 2:
        return array if stop == 2 else lex(stop, n + 1, array)

    new = [nested[:] for _ in range(n) for nested in array]

    for x, nested in enumerate(new):
        pos = x // factorial(n - 1)
        nested.insert(pos, -pos)
        for y in range(pos):
            nested[y] += 1

    return new if n == stop else lex(stop, n + 1, new)
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks for the quick answer and recommendation about the default arguments. – robjtede May 15 '14 at 13:44
  • Wow, that new code just blew my mind. I'm really quite new to Python and many of these cool ways of doing things aren't available in JS. – robjtede May 15 '14 at 13:50