时间:2021-05-22
利用动态规划算法,实现最短编辑距离的计算。
复制代码 代码如下:
#encoding: utf-8
#author: xu jin
#date: Nov 12, 2012
#EditDistance
#to find the minimum cost by using EditDistance algorithm
#example output:
# "Please input a string: "
# exponential
# "Please input the other string: "
# polynomial
# "The expected cost is 6"
# The result is :
# ["e", "x", "p", "o", "n", "e", "n", "-", "t", "i", "a", "l"]
# ["-", "-", "p", "o", "l", "y", "n", "o", "m", "i", "a", "l"]
p "Please input a string: "
x = gets.chop.chars.map{|c| c}
p "Please input the other string: "
y = gets.chop.chars.map{|c| c}
x.unshift(" ")
y.unshift(" ")
e = Array.new(x.size){Array.new(y.size)}
flag = Array.new(x.size){Array.new(y.size)}
DEL, INS, CHA, FIT = (1..4).to_a #deleat, insert, change, and fit
def edit_distance(x, y, e, flag)
(0..x.length - 1).each{|i| e[i][0] = i}
(0..y.length - 1).each{|j| e[0][j] = j}
diff = Array.new(x.size){Array.new(y.size)}
for i in(1..x.length - 1) do
for j in(1..y.length - 1) do
diff[i][j] = (x[i] == y[j])? 0: 1
e[i][j] = [e[i-1][j] + 1, e[i][j - 1] + 1, e[i-1][j - 1] + diff[i][j]].min
if e[i][j] == e[i-1][j] + 1
flag[i][j] = DEL
elsif e[i][j] == e[i-1][j - 1] + 1
flag[i][j] = CHA
elsif e[i][j] == e[i][j - 1] + 1
flag[i][j] = INS
else flag[i][j] = FIT
end
end
end
end
out_x, out_y = [], []
def solution_structure(x, y, flag, i, j, out_x, out_y)
case flag[i][j]
when FIT
out_x.unshift(x[i])
out_y.unshift(y[j])
solution_structure(x, y, flag, i - 1, j - 1, out_x, out_y)
when DEL
out_x.unshift(x[i])
out_y.unshift('-')
solution_structure(x, y, flag, i - 1, j, out_x, out_y)
when INS
out_x.unshift('-')
out_y.unshift(y[j])
solution_structure(x, y, flag, i, j - 1, out_x, out_y)
when CHA
out_x.unshift(x[i])
out_y.unshift(y[j])
solution_structure(x, y, flag, i - 1, j - 1, out_x, out_y)
end
#if flag[i][j] == nil ,go here
return if i == 0 && j == 0
if j == 0
out_y.unshift('-')
out_x.unshift(x[i])
solution_structure(x, y, flag, i - 1, j, out_x, out_y)
elsif i == 0
out_x.unshift('-')
out_y.unshift(y[j])
solution_structure(x, y, flag, i, j - 1, out_x, out_y)
end
end
edit_distance(x, y, e, flag)
p "The expected edit distance is #{e[x.length - 1][y.length - 1]}"
solution_structure(x, y, flag, x.length - 1, y.length - 1, out_x, out_y)
puts "The result is : \n #{out_x}\n #{out_y}"
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
-AUC计算方法-AUC的Python实现方式AUC计算方法AUC是ROC曲线下的面积,它是机器学习用于二分类模型的评价指标,AUC反应的是模型对样本的排序能力
本文实例讲述了Java滚动数组计算编辑距离操作。分享给大家供大家参考,具体如下:编辑距离(EditDistance),也称Levenshtein距离,是指由一个
本文实例讲述了PHP计算百度地图两个GPS坐标之间距离的方法。分享给大家供大家参考。具体实现方法如下:复制代码代码如下:/***计算两个坐标之间的距离(米)*@
拼多多的品质退款率计算方法一直被不少商家所诟病,现在这点也做出了相应的更新,下面来看看具体更新内容: 一、品质退款数据计算方法更改 与之前顾客发起退款,
到底整数分区会得到整数的容量结果?分区计算方法:较早时间的计算方法为:MB=(G-1)*4+1024*G该方法用于早期的FAT32分区所得到的结果比较准确,但用