最长的公共子序列实现-python [英] Longest common subsequence implementation-python

查看:80
本文介绍了最长的公共子序列实现-python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已按照此视频中的指示,实现了最长的常见子序列问题.它只执行第一组代码并产生一个空列表.此实现有什么问题?

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) 

推荐答案

if not xlist or ylist:将评估为if (not xlist) or (ylist),因此,如果将Truthy(如非空列表)传递给ylist,它将始终评估为True.您可能想要:

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 []

或者,您可以使用:

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

这篇关于最长的公共子序列实现-python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆