简体   繁体   中英

Recursion showing error for finding longest common sub-sequence in python

This is the ideone link . I want to solve the famous lcs problem by dynamic programming, but can't figure this error out. It says as following when I run this function:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

a = "ABCBDABA"
b = "BDCABAD"
d = dict()
def lcs(m, n):
    if m == 0 or n == 0:
        return 0
    key = str(m) + "|" + str(n)
    if key not in d.keys():
        #print(key)           
        if a[m - 1] == b[n - 1]:
            d[key] = lcs(m - 1, n - 1) + 1
        else:
            d[key] = max(lcs(m - 1, n), lcs(m, n - 1))
    else:
        return d[key]

lcs(len(a), len(b))
print(d)

What line is the error occurring on? I'm guessing that it's the line

d[key] = lcs(m - 1, n - 1) + 1

because the error is saying that you're adding two objects, one of type int and one that has no specified type (which Python calls NoneType ). This means that your lcs function is not returning anything when you give it the inputs m - 1 and n - 1 . This is happening because the only return statement in your function occurs in the outermost else condition.

That is to say, you need your function to return something, an integer perhaps, when the key str(m) + "|" + str(n) str(m) + "|" + str(n) is not in the dictionary.

I don't know if this is the output you're looking for, but I added a return statement:

a = "ABCBDABA"
b = "BDCABAD"
d = dict()
def lcs(m, n):
    if m == 0 or n == 0:
        return 0
    key = str(m) + "|" + str(n)
    if key not in d.keys():
        #print(key)           
        if a[m - 1] == b[n - 1]:
            d[key] = lcs(m - 1, n - 1) + 1
        else:
            d[key] = max(lcs(m - 1, n), lcs(m, n - 1))
        return d[key]
    else:
        return d[key]

lcs(len(a), len(b))
print(d)

and now the above code, when run, returns:

{'1|6': 1, '1|4': 1, '2|5': 2, '2|6': 2, '1|1': 0, '1|2': 0, '1|3': 0, '2|1': 1, '2|2': 1, '2|3': 1, '2|4': 1, '3|3': 2, '3|4': 2, '3|5': 2, '3|6': 2, '4|5': 3, '4|6': 3, '5|7': 4, '3|1': 1, '3|2': 1, '4|1': 1, '4|2': 1, '4|3': 2, '4|4': 2, '5|2': 2, '5|3': 2, '5|4': 2, '5|5': 3, '6|6': 4, '6|7': 4, '6|4': 3, '7|5': 4, '7|6': 4, '7|7': 4, '8|6': 5, '8|7': 5}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM