0

This is a standart permutation function. Im tring to return the list of the lists of the permutations) Could you help me with storaging the result of the recursion iterations? for example this code returns nonsense. It would be perfect if there was no global variable and rezulting list was inside the func

Thanks!

'''

z=[]
def func(N,M=-1,pref=None):
global z
if M == -1:
    M = N
pref = pref or []
if M==0:
    z.append(pref)
    print(pref)
for i in range(N):
    if i not in pref:
        pref.append(i)
        func(N,M-1,pref)
        pref.pop()

func(3)
print(z)

'''

Umair Mubeen
  • 823
  • 4
  • 22
Efor
  • 1

2 Answers2

0

You are passing a list (pref variable in for loop) reference to your function and you are removing a single item from that and that's why you are ending with an empty list z.

Create a new list or copy the list before passing it to the function to avoid this situation.

z = []


def func(N, M=-1, pref=None):
    global z
    if M == -1:
        M = N
    pref = pref or []
    if M == 0:
        z.append(pref)
        print(pref)
    for i in range(N):
        if i not in pref:
            pref.append(i)
            func(N, M - 1, pref[:])
            pref.pop()


func(3)
print(z)

For better understand please read this one. List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

Alif Jahan
  • 793
  • 1
  • 7
  • 20
-1

If you want to have some kind of accumulator you must pass it to the recursion function, beware it could be a little nightmare.

Andrea Pollini
  • 292
  • 4
  • 8