文件比较算法(1)


# -*- coding: cp936 -*-
'''
文件比较算法:
算法模型参见:
# 参考文章:http://blog.csdn.net/clariones/archive/2006/11/19/1396880.aspx
# http://blog.csdn.net/clariones/archive/2006/11/24/1412394.aspx
1.确定最大匹配率
2.确定最优匹配路径
'''
left = 'ABCACADF'
right = 'BCXCADFESBABCACA'
all = []
# 创建矩阵,行数与列数均为left,right的长度+1,并将所有元素置0
for i in range(len(left) + 1):
    all.append([])
    for j in range(len(right) + 1):
        all.append(0)
##for i in all:
## print i
# 比较left与right的值,相同的将矩阵中对应元素置1
for l in range(len(left)):
    for r in range(len(right)):
        if left[l] == right[r]:
            all[l][r] = 1
##print '*'* 10
##for i in all:
## print i
# 计算最大匹配数
for i in range(len(left) - 1,-1,-1):
    for j in range(len(right) - 1,-1,-1):
        all[j] = max(all[j+1],all[i+1][j+1]+ all[j],all[i+1][j])
print '*' * 20
for i in all:
    print i
# 计算最短路径
for j in range(len(right) - 1,-1,-1):
    for i in range(len(left) - 1,-1,-1):
        if left == right[j]:
            all[j] = all[i + 1][j + 1] + 1
        else:
            if all[i + 1][j] >= all[j + 1]:
                all[j] = all[i + 1][j]
            else:
                all[j] = all[j+1] + 1
print '*' * 20
for i in all:
    print i