Longest common subsequence implementation-python

北战南征 提交于 2019-12-11 02:23:21

问题


I have implemented the longest common subsequence problem as instructed in this video. It just execute first set of code and produces an empty list. What is wrong with this implementation?

def lcs_recursive(xlist,ylist):
    if not xlist or ylist:
        return []
    x,xs,y,ys, = xlist[0],xlist[1:],ylist[0],ylist[1:]
    if x == y:
        return [x] + lcs_recursive(xs,ys)
    else:
        return max(lcs_recursive(xlist,ys),lcs_recursive(xs,ylist),key=len)



s1 = 'abc'
s2 = 'aeb'

print lcs_recursive(s1,s2) 

回答1:


if not xlist or ylist: will evaluate as if (not xlist) or (ylist) and as such if you pass in something Truthy (like a non-empty list) to ylist it will always evaluate to True. You probably want:

if not xlist or not ylist:
    return []

Alternatively you could use:

if not all([xlist, ylist]):
    return []


来源:https://stackoverflow.com/questions/25930671/longest-common-subsequence-implementation-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!