0

The code I'm trying to write is pretty simple. I'm trying to generate permutations of all the numbers up to 'n' and return the list of those values. For example if n = 2, the output will be:

[[1,1],[1,2],[2,1],[2,2]]

The code is as follows:

def compute_arr(ind, limit, cnt, so_far, lst):
    # if count == limit, append so_far to lst
    if cnt == limit:
        lst.append(so_far)
        return
    # else continue building the list with every permutation from 1 to n
    for t in range(1, limit+1):
        so_far[cnt] = t
        return compute_arr(t, limit, cnt+1, so_far, lst)

def compute():
    n = 2
    so_far, lst = list(range(n)), list()
    compute_arr(0, n, 0, so_far , lst)
    print(lst)

When I print each of the 'so_far' elements as I am appending into 'lst', I can see the correct values being appended. However when I print out the value of the final list, it appears to all have the same final value. For example, for n = 2, the output is:

[[2,2],[2,2],[2,2],[2,2]]

I assumed that Python always passes by reference. Am I doing something wrong here?

Vinay Pai
  • 443
  • 1
  • 5
  • 13
  • Just a heads up, there's a library for that. [`itertools`](https://docs.python.org/2/library/itertools.html) with the function [`itertools.permutations`](https://docs.python.org/2/library/itertools.html#itertools.permutations) – Moon Cheesez Jul 24 '16 at 07:35
  • Yes :) Im in a coding competition which has disabled this library :) – Vinay Pai Jul 24 '16 at 07:35
  • FWIW, those aren't permutations. That's the Cartesian product. – PM 2Ring Jul 24 '16 at 08:00
  • Thanks @icktoofay. Can you suggest how the code can be modified so as to handle pass by value along with recursion? Im out of ideas! – Vinay Pai Jul 24 '16 at 08:06

0 Answers0