Search code examples
pythonpseudocode

Translate Pseudocode into python


Below is the pseudocode to calculate an adaptation of the Levenstein minimum distance. I have the first part decoded for python but I can't figure out the bottom part, denoted with ***.

Algorithm of distance calculation (pseudocode) using dynamical programming:

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

Solution

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