-1
N,M=map(int,input().split())

ans=[]
lst=[]

def dfs(num):
    global ans
    if(num==M):
        ans.append(lst)
        return

    for i in range(1,N+1):
        if(i not in lst):
            lst.append(i)
            dfs(len(lst))
            print(ans)
            lst.pop()
            print(ans)

dfs(0)

print(ans)

this is my code. This is example code, when I put N=4, M=1. execution result

I don't understand why my list called ans is reset, when after 'lst.pop()' Two lists are actually seperated lists. Thank you

Swifty
  • 2,630
  • 2
  • 3
  • 21
seog
  • 3
  • 1
  • 7
    *"Two lists are actually seperated lists."* They actually aren't. When you do `ans.append(lst)`, that means that `ans` contains the `lst` object itself, not a copy of `lst`. See https://stackoverflow.com/questions/2612802/how-do-i-clone-a-list-so-that-it-doesnt-change-unexpectedly-after-assignment – slothrop Aug 17 '23 at 09:03
  • 4
    It might help if you included in your question the expected result for your example. – Swifty Aug 17 '23 at 09:04
  • Try it on http://pythontutor.com. – deceze Aug 17 '23 at 09:18

1 Answers1

1

ans.append(lst) uses the reference of 'lst', so when you do lst.pop(), the change is reflected in 'ans' also. You need to create a copy of the 'lst', i.e. ans.append(lst.copy())

N,M=4,1

ans=[]
lst=[]

def dfs(num):
    global ans
    if(num==M):
        #Appending a copy of the 'lst' List
        ans.append(lst.copy())
        return

    for i in range(1,N+1):
        if(i not in lst):
            lst.append(i)
            dfs(len(lst))
            print(ans)
            lst.pop()
            print(ans)

dfs(0)

print("Final:",ans)

output

[[1]]
[[1]]
[[1], [2]]
[[1], [2]]
[[1], [2], [3]]
[[1], [2], [3]]
[[1], [2], [3], [4]]
[[1], [2], [3], [4]]
Final: [[1], [2], [3], [4]]
KRG
  • 655
  • 7
  • 18