python 最长公共子序列
2015-12-24 17:00
435 查看
网上有很多,但有bug,特别是这个:http://www.oschina.net/code/snippet_16840_2015 好大的坑...
get length
get string
use into app
get length
def lcs_len(a,b): c = [[0 for j in b] for i in a] for i in range(len(a)): for j in range(len(b)): if i==0 or j==0: continue if a[i]==b[j]: c[i][j] = c[i-1][j-1]+1 else: c[i][j] = max(c[i-1][j],c[i][j-1]) return c[i][j]
get string
def lcs_string(a,b): lena,lenb = len(a),len(b) # length table c = [[0 for i in b] for j in a] # direction table flag = [[0 for i in b] for j in a] for i in range(lena): for j in range(lenb): if i==0 or j==0: continue if a[i]==b[j]: c[i][j] = c[i-1][j-1]+1 flag[i][j] = 3 elif c[i-1][j]<c[i][j-1]: c[i][j] = c[i][j-1] flag[i][j] = 2 else: c[i][j] = c[i-1][j] flag[i][j] = 1 (p1,p2) = (lena-1,lenb-1) s = [] while 1: d = flag[p1][p2] if d == 3: s.append(a[p1]) p1 -= 1 p2 -= 1 elif d == 2: p2 -= 1 elif d == 1: p1 -= 1 if p1==0 or p2==0: # solve the first element without print problem if a[p1]==b[p2]: s.append(a[p1]) break s.reverse() return ''.join(s)
use into app
def lcs_from_list(input,jobnames): if input in jobnames: return input res = [(lcs_len(input,jobname),jobname) for jobname in jobnames] res.sort() return res[-1][1]
相关文章推荐
- Python
- 我写的WEBPY框架的 提供验证码识别的PYTHON 程序
- python基础----map和reduce
- python之socket
- winpython好用到哭了,自带numpy,scipy,matplotlib,scikit-learn
- 有一个fuck叫做wfg,还是大写---python的@修饰符解析
- Python学习笔记----面向对象(类)
- ArcGIS中python实现地图服务的自动发布
- python逐行读取文件内容的三种方法
- Python学习笔记,我的一个PyQt工程,一:Python是什么鬼?
- Python学习笔记,我的一个PyQt工程,一:Python是什么鬼?
- Python学习遇到的问题
- Python之抓取动态网页
- python的cls,self,classmethod,staticmethod
- 在cmd等终端运行python代码,文件
- 【python】日志系统
- python的第一个程序
- python 定制类
- 【python】if __name__ == '__main__'
- 在Mac OS上搭建Python的开发环境