将伪代码转换为python

时间:2015-04-19 16:18:27

标签: python pseudocode

下面是计算Levenstein最小距离的自适应的伪代码。我有第一部分解码为python但我无法弄清楚底部,用***表示。

使用动态规划的距离计算算法(伪代码):

First Part:

int function distance(Sequence sequence1, Sequence sequence2)
  set length_1 to length of sequence1
  set length_2 to length of sequence2

declare distances[length_1+1][length_2+1]

for i from 0 to length_1
  set distances[i][0] to i

for j from 0 to length_2
  set distances[0][j] to j

// Classical Levenshtein part
for i = 1 to length_1
  for j = 1 to length_2
    set cost to 0
    if (sequence1[i-1] not equal to sequence[j-1])
      set cost to 1
    set distances[i][j] to minimum of
          distances[i-1][j-1] + cost,// Substitution
          distances[i][j-1] + 1, // Insertion
          distances[i-1][j] + 1 // Deletion

set min_distance to distances[length_1][length_2]

******New Part- Help!*******
// Truncating
for i from 0 to length_1
  set min_distance to minimum of min_distance and distances[i][length_2]
// Elongating
for j from 0 to length_2
  set min_distance to minimum of min_distance and distances[length_1][j]
return min_distance

1 个答案:

答案 0 :(得分:0)

return min(itertools.chain((x[length_2] for x in distances),
  distances[length_1]))