python3 lcs 最大公用子序列

來源:互聯網
上載者:User

標籤:相等   info   python3   pytho   color   rect   實現   sign   技術   

拋出問題:

  假定字串 s1 = ‘BDCABA‘, s2 = ‘ABCBDAB‘,求s1和s2的最大公用子序列。

問題分析:

  我們想要求出s1和s2的最大公用子序列,我們可以用c(i,j)表示s1(i)和s2(j)最大公用子序列的長度,

   假定c(i,j) = m,

     如果:s1[ i ]和s2[ j ]相等,那麼推出c(i,j) = c(i-1,j-1)  + 1,

  如果:s1[ i ] 和 s2[ j ]不相等,那麼得到c(i,j) = max(c(i,j-1),c(i-1,j))

  總結為公式就是:

畫成表格更清楚,也就是如,表格的數即為當前的最大公用子序列的值,箭頭即為該結果是怎麼得來的

例如第5行,第5列,因為第5列的c和第5行c相等,所以就等於,第4行,第4列的值+1等到2

  得到了這個值列表,就可以通過回溯的方法,從最後一個值,倒著按照箭頭的方向,依次記錄每個相等的值(也就是方向是左上的值),得到的結果就是我們要求的最終結果

代碼實現:
# -*- coding:utf-8  -*-# 日期:2018/6/9 15:44# Author:小滑鼠# 求最長公用子序列from numpy import *s1 = ‘BDCABA‘s2 = ‘ABCBDAB‘def val_list(s1,s2):    # 兩個字串的長度    len_s1 = len(s1) + 1    len_s2 = len(s2) + 1    # 方向列表    direction_list = []    # 產生len_s2+1行len_s1+1列的全0列表    res = zeros((len_s2,len_s1))    direction = zeros((len_s2,len_s1))    # print(res_list)    for i in range(0, len_s2-1):        for j in range(0, len_s1-1):            #判斷是否相等            if s1[j] == s2[i]:                res[i + 1, j + 1] = res[i, j] + 1                # 1左上 2 上 3左                direction[i + 1, j + 1] = 1            else:                if res[i + 1, j] > res[i, j + 1]:                    res[i + 1, j + 1] = res[i + 1, j]                    direction[i + 1, j + 1] = 3                else:                    res[i + 1, j + 1] = res[i, j + 1]                    direction[i + 1, j + 1] = 2    return res,directionres ,direction= val_list(s1,s2)#方向列表 1左上 2 上 3左# [[0. 0. 0. 0. 0. 0. 0.]#  [0. 2. 2. 2. 1. 3. 1.]#  [0. 1. 3. 3. 2. 1. 3.]#  [0. 2. 2. 1. 3. 2. 2.]#  [0. 1. 2. 2. 2. 1. 3.]#  [0. 2. 1. 2. 2. 2. 2.]#  [0. 2. 2. 2. 1. 2. 1.]#  [0. 1. 2. 2. 2. 1. 2.]]#最大子序列的值列表# [[0. 0. 0. 0. 0. 0. 0.]# [0. 0. 0. 0. 1. 1. 1.]# [0. 1. 1. 1. 1. 2. 2.]# [0. 1. 1. 2. 2. 2. 2.]# [0. 1. 1. 2. 2. 3. 3.]# [0. 1. 2. 2. 2. 3. 3.]# [0. 1. 2. 2. 3. 3. 4.]# [0. 1. 2. 2. 3. 4. 4.]]#回溯 遞迴求出結果global s_ress_res = ‘‘def Lcs_fun(s,res_list,i,j):    if res_list[i,j] == 3:        Lcs_fun(s,res_list,i,j-1)    elif res_list[i,j] == 2:        Lcs_fun(s,res_list,i-1,j)    elif res_list[i,j] == 1:        Lcs_fun(s,res_list,i-1,j-1)        global s_res        s_res += s[i-1]    else:        returnLcs_fun(s2,direction,len(s2),len(s1))print(s_res)

這塊很容易就看暈了,仔細看,應該能看懂

 

python3 lcs 最大公用子序列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.