0

I have 2 sequences and need to find longest common subsequence. Can't figure out why my function restore does not work.

#sequenses
A=[1,2,3]
B=[2,3,1,5]
#table AxB
rows=[0]*(len(B)+1)
table=[rows for l in range(len(A)+1)]
for i in range(len(A)):
    for k in range(len(B)):
        if A[i]==B[k]:
            table[i+1][k+1]=table[i][k]+1
        else:
            table[i+1][k+1]=max(table[i][k+1], table[i+1][k])
print(table)
lst=[]#subsequence
#function to restore subsequence by walking through table
def restore(s1,s2):#s1=len(A)-1, s2=len(B)-1
    if s1==-1 or s2==-1:
        pass
    elif A[s1]==B[s2]:
        print (1)
        lst.append(A[s1])
        restore(s1-1, s2-1)
    else:
        if table[s1][s2+1]==table[s1+1][s2+1]:
            restore(s1-1,s2)
        else:
            restore(s1, s2-1)
    return lst

If I do

print (restore(2,3)) 

function return

[]

I think, that problem is in indexes, but can't find where it is.

Alice V.
  • 53
  • 1
  • 3

1 Answers1

0

Here's your first problem:

rows=[0]*(len(B)+1)
table=[rows for l in range(len(A)+1)]

Python uses references for lists. So when you make a bunch of rows, it is actually multiple references to the same rows list. Take a look at this test code:

>>> rows = [0]*5
>>> table = [rows for l in range(5)]
>>> table
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> table[0][2] = 4
>>> table
[[0, 0, 4, 0, 0], [0, 0, 4, 0, 0], [0, 0, 4, 0, 0], [0, 0, 4, 0, 0], [0, 0, 4, 0, 0]]

See how the single change was repeated? That's because I have 5 references to the same list, instead of 5 lists. Try this:

table = [None]*(len(A)+1)
for i in range(len(table)):
    table[i] = [0]*(len(B)+1)
wrongu
  • 560
  • 3
  • 13