python 最长公共子序列长度,Python:列表的最长公共子序列的长度

这篇博客介绍了如何使用动态规划方法在Python中找到两个列表的最长公共子序列(LCS)的长度。提供了两种实现,分别计算LCS的长度和最长公共子串的长度。示例代码展示了如何应用这些方法,并给出了具体的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Is there a built-in function in python which returns a length of longest common subsequence of two lists?

a=[1,2,6,5,4,8]

b=[2,1,6,5,4,4]

print a.llcs(b)

>>> 3

I tried to find longest common subsequence and then get length of it but I think there must be a better solution.

解决方案

You can easily retool a LCS into a LLCS:

def lcs_length(a, b):

table = [[0] * (len(b) + 1) for _ in xrange(len(a) + 1)]

for i, ca in enumerate(a, 1):

for j, cb in enumerate(b, 1):

table[i][j] = (

table[i - 1][j - 1] + 1 if ca == cb else

max(table[i][j - 1], table[i - 1][j]))

return table[-1][-1]

Demo:

>>> a=[1,2,6,5,4,8]

>>> b=[2,1,6,5,4,4]

>>> lcs_length(a, b)

4

If you wanted the longest common substring (a different, but related problem, where the subsequence is contiguous), use:

def lcsubstring_length(a, b):

table = [[0] * (len(b) + 1) for _ in xrange(len(a) + 1)]

l = 0

for i, ca in enumerate(a, 1):

for j, cb in enumerate(b, 1):

if ca == cb:

table[i][j] = table[i - 1][j - 1] + 1

if table[i][j] > l:

l = table[i][j]

return l

This is very similar to the lcs_length dynamic programming approach, but we track the maximum length found so far (since it is no longer guaranteed the last element in the table is the maximum).

This returns 3:

>>> lcsubstring_length(a, b)

3

A sparse table variant to not have to track all the 0s:

def lcsubstring_length(a, b):

table = {}

l = 0

for i, ca in enumerate(a, 1):

for j, cb in enumerate(b, 1):

if ca == cb:

table[i, j] = table.get((i - 1, j - 1), 0) + 1

if table[i, j] > l:

l = table[i, j]

return l

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值