Home > OS >  getting empty list even though appending while using recursion
getting empty list even though appending while using recursion

Time:02-15

I am trying to print all subsequences of the list "l" in the code but here i want the answer to be stored in "proc" list.But when executing the below code i am getting empty lists of list.I am practising recursion problems.I stuck to understand why i am getting empty lists of list which is "proc" list

proc = [] #global array
def fun(t,lst,i,n):
    if(i==n):
        print(t)
        proc.append(t) #appending to the global array
        return
    t.append(lst[i])
    fun(t,lst,i 1,n)
    t.pop()
    fun(t,lst,i 1,n)

arr = [6,4,2]
n = len(arr)
l = []
for i in range(n):
    for j in range(i 1,n):
        l.append([i 1,j 1])
fun([],l,0,len(l))
print(proc) #printing the global list proc after executing function```

I want to know why i am getting output as empty lists even though i am appending "t" list to the "proc" list


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


i want answer to be appended list of t

CodePudding user response:

You have fallen prey to one of the classic Python errors. You are passing [] into the function as t. You then modify t, and pass t into the recursive call. That means there is ONLY ONE LIST t. When you do proc.append(t), you are not grabbing a snapshot of the array. You are appending multiple references to that one list. By the time the function ends, t is empty, so your proc has multiple references to an empty list.

The short term fix is to change to

    proc.append( t.copy() )

or

    proc.append( t[:] )
  • Related