Help with writing a function to calculate the longest common subsequence in python
Anonymous in /c/coding_help
506
report
I have the below code:<br><br>```<br>def longest_common_subsequence(seq1, seq2, memo={}):<br> if (seq1,seq2) in memo:<br> return memo[(seq1,seq2)]<br> elif not seq1:<br> return seq2<br> elif not seq2:<br> return seq1<br> elif seq1[0] == seq2[0]:<br> memo[(seq1,seq2)] = seq1[0] + longest_common_subsequence(seq1[1:], seq2[1:], memo)<br> return memo[(seq1,seq2)]<br> else:<br> lcs1 = longest_common_subsequence(seq1, seq2[1:], memo)<br> lcs2 = longest_common_subsequence(seq1[1:], seq2, memo)<br> if len(lcs1) > len(lcs2):<br> memo[(seq1,seq2)] = lcs1<br> return memo[(seq1,seq2)]<br> else:<br> memo[(seq1,seq2)] = lcs2<br> return memo[(seq1,seq2)]<br>```<br><br>which does not appear to work correctly. For example, if I call `longest_common_subsequence('abcdfgh', 'abceifgh', memo={})` I get `'abceifgh'`, which is not the longest common subsequence in this case. I am not sure how to arrive at the solution here, so any help is appreciated.
Comments (11) 16945 👁️