zoukankan      html  css  js  c++  java
  • 最长公共子序列lcs实现

    def lcs(s1, s2):
        m = len(s1)         # 记录s1长度
        n = len(s2)         # 记录s2长度
        a = [[0 for j in range(n+1)]for i in range(m+1)]        # 得分数组
        b = [[0 for j in range(n+1)]for i in range(m+1)]        # 路径方向数组
        for i in range(1, m+1):
            for j in range(1, n+1):
                if s1[i-1] == s2[j-1]:          # 当前字符相同,左上对角加1
                    a[i][j] = a[i-1][j-1] + 1
                    b[i][j] = 1
                elif a[i][j-1] > a[i-1][j]:     # 之前最长序列由左边得到
                    a[i][j] = a[i][j-1]
                    b[i][j] = 2
                else:
                    a[i][j] = a[i-1][j]         # 之前最长序列由上边得到
                    b[i][j] = 3
        return a[m][n], b                       # 返回公共序列的长度及方向矩阵
    
    def lcs_traceback(s1, s2):
        """ 路径回溯
        :param s1:
        :param s2:
        :return:
        """
        a, b = lcs(s1, s2)
        i = len(s1)
        j = len(s2)
        res = []
        while i > 0 and j > 0:      # 有一个字符为0时,循环停止
            if b[i][j] == 1:
                res.append(s1[i-1]) # 能够取到的下标是i-1
                i -= 1
                j -= 1
            elif b[i][j] == 2:
                j -= 1
            else:
                i -= 1
        print(b)
        print("{}".format(list(reversed(res))))
    
    
    if __name__ == '__main__':
        lcs_traceback("abcde", "bcdfe")

    结果显示:

    时刻记着自己要成为什么样的人!
  • 相关阅读:
    @Controller @RestController
    HOMEWORD2
    cudnn、cuda
    jupyter使用
    python学习——os模块
    python学习——导入模块、__name__
    python学习——文件
    python学习——函数、内置函数
    python学习——for循环的应用
    python学习——字典、集合、数据类型总结
  • 原文地址:https://www.cnblogs.com/demo-deng/p/14687174.html
Copyright © 2011-2022 走看看