# -*- 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.确定最优匹配路径
'''
right = 'ABCACADF'
left = 'BCXCADFESBABCACA'
all = []
# 创建矩阵,行数与列数均为left,right的长度+1,并将所有元素置0
for l in range(len(left) + 1):
all.append([])
for r in range(len(right) + 1):
all[l].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 l in range(len(left) - 1,-1,-1):
for r in range(len(right) - 1,-1,-1):
all[l][r] = max(all[l][r+1],all[l+1][r+1]+ all[l][r],all[l+1][r])
##print '*' * 20
for i in all:
print i
'''
最大匹配数结果,注意最后一行和一列
[6, 6, 5, 4, 4, 3, 2, 1, 0]
[6, 5, 5, 4, 4, 3, 2, 1, 0]
[6, 5, 4, 4, 4, 3, 2, 1, 0]
[6, 5, 4, 4, 4, 3, 2, 1, 0]
[6, 5, 4, 3, 3, 3, 2, 1, 0]
[6, 5, 4, 3, 2, 2, 2, 1, 0]
[6, 5, 4, 3, 2, 1, 1, 1, 0]
[6, 5, 4, 3, 2, 1, 0, 0, 0]
[6, 5, 4, 3, 2, 1, 0, 0, 0]
[6, 5, 4, 3, 2, 1, 0, 0, 0]
[6, 5, 4, 3, 2, 1, 0, 0, 0]
[5, 5, 4, 3, 2, 1, 0, 0, 0]
[4, 4, 4, 3, 2, 1, 0, 0, 0]
[3, 3, 3, 3, 2, 1, 0, 0, 0]
[2, 2, 2, 2, 2, 1, 0, 0, 0]
[1, 1, 1, 1, 1, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
'''
### 计算最短路径
for l in range(len(left) - 1,-1,-1):
for r in range(len(right) - 1,-1,-1):
if left[l] == right[r]:
all[l][r] = all[l + 1][r + 1] + 1
else:
if all[l][r+1] >= all[l+1][r]:
all[l][r] = all[l][r + 1]
else:
all[l][r] = all[l+1][r] + 1
print '*' * 20
for i in all:
print i
'''
最优匹配路径计算结果,注意最后一行和一列
[16, 14, 14, 14, 7, 7, 7, 7, 0]
[15, 15, 13, 13, 6, 6, 6, 6, 0]
[14, 14, 12, 12, 5, 5, 5, 5, 0]
[13, 13, 11, 11, 4, 4, 4, 4, 0]
[12, 12, 12, 10, 10,3, 3, 3, 0]
[11, 11, 11, 9, 9, 6, 2, 2, 0]
[10, 10, 10, 8, 8, 5, 1, 1, 0]
[9, 9, 9, 7, 7, 4, 0, 0, 0]
[8, 8, 8, 6, 6, 3, 0, 0, 0]
[7, 7, 7, 5, 5, 2, 0, 0, 0]
[6, 6, 6, 4, 4, 1, 0, 0, 0]
[5, 5, 5, 5, 3, 3, 0, 0, 0]
[4, 4, 4, 4, 2, 2, 0, 0, 0]
[3, 3, 3, 3, 3, 1, 0, 0, 0]
[2, 2, 2, 2, 2, 2, 0, 0, 0]
[1, 1, 1, 1, 1, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
'''
|