我已经按照本中的说明实现了最长公共子序列问题video https://www.youtube.com/watch?v=xnWqLAI3TKs。它只执行第一组代码并生成一个空列表。这个实现有什么问题吗?
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 not ylist:
return []
或者你可以使用:
if not all([xlist, ylist]):
return []
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)