Python recursive call not executing code - Longest common of subsequence of 3 sequences

63 views Asked by At
def lcs3(a, b, c, an, bn, cn):
global arr
print(an,bn,cn,end=" ")
print(arr[an][bn][cn],end="/ ")
if arr[an][bn][cn] != None:
    print ("Already here")
    return arr[an][bn][cn]
if an == 0 or bn == 0 or cn == 0:
    arr[an][bn][cn] = 0
    print("One of 3 inputs is 0")
elif a[an-1] == b[bn-1] and b[bn-1] == c[cn-1]:
    print("match!", an, bn, cn)
    arr[an][bn][cn] = lcs3(a,b,c,an-1,bn-1,cn-1)+1
else:
    print("Calculating")
    arr[an][bn][cn] = max(lcs3(a,b,c,an-1,bn,cn),
                          lcs3(a,b,c,an,bn-1,cn),
                          lcs3(a,b,c,an,bn,cn-1))
return arr[an][bn][cn]

Here is a function I have of calculating the longest common subsequence by taking in 3 sequences and the length of the sequences as inputs. The algorithm is dynamic programming with a top-down aproach, and arr is defined outside the function (3 dimensional list with an+1,bn+1,cn+1 as the size)

Edit: The printing issue has been resolved but I'm still getting an incorrect answer. For input

5

8 3 2 1 7

7

8 2 1 3 8 10 7

6

6 8 3 1 4 7

I get 2 returned.

1

There are 1 answers

0
WestaAlger On

Simple answer:

if arr[an][bn][cn] != None: return arr[an][bn][cn] print("Already in arr")

You're returning before you print in the first if statement.