I am trying to solve the longest common subsequence problem using recursion. I have written the following code for it. However I am encountering the same error each time and I am unable to make sense of it.
class LCS:
def __init__(self, seq1, seq2):
self.seq1 = seq1
self.seq2 = seq2
def recursive_LCS(self, index1 = 0, index2 = 0):
# Terminating condition when either of the substring is empty
if (self.seq1[index1:] == "") or (self.seq2[index2:] == ""):
return 0
# When first elements of the substrings match, we increase both the index by 1
elif self.seq1[index1] == self.seq2[index2]:
return 1+ LCS.recursive_LCS(index1+1, index2+1)
# When the first elements dont match, we split into two cases and choose the one with max matches
else:
return max(LCS.recursive_LCS(index1+1, index2), LCS.recursive_LCS(index1, index2+1))
str1 = "set"
str2 = "bet"
sub1 = LCS(str1, str2)
print(sub1.recursive_LCS())
This is the error message I am encountering
Exception has occurred: AttributeError'int' object has no attribute 'seq1'File "C:\Users\ACER\Desktop\Python Practice\test.py", line 10, in recursive_LCSif (self.seq1[index1:] == "") or (self.seq2[index2:] == ""):^^^^^^^^^File "C:\Users\ACER\Desktop\Python Practice\test.py", line 17, in recursive_LCSreturn max(LCS.recursive_LCS(index1+1, index2), LCS.recursive_LCS(index1, index2+1))^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "C:\Users\ACER\Desktop\Python Practice\test.py", line 22, in <module>print(sub1.recursive_LCS())^^^^^^^^^^^^^^^^^^^^AttributeError: 'int' object has no attribute 'seq1'
I am new to recursion and Object Oriented Approach hence i am unable to make any sense of what is resulting in this error, would really appreciate the help.
This problem is related to how you call: LCS.recursive_LCS(index1+1, index2)
. Your self
here is index1+1
which is definitely not what you want. You should use self.recursive_LCS(index1+1, index2)
.
I've tested and it seems working!