/
alignment.py
45 lines (36 loc) · 1.11 KB
/
alignment.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# alignment.py: Reads from standard input, the output produced by
# edit_distance.py, i.e., input strings x and y, and the opt matrix. The
# program then recovers an optimal alignment from opt, and writes to
# standard output the edit distance between x and y and the alignment itself.
# Import necessary modules.
import stdio
import stdarray
# Read x, y, and opt from standard input.
x = stdio.readString()
y = stdio.readString()
opt = stdarray.readInt2D()
# Compute M and N.
M = len(x)
N = len(y)
# Write edit distance between x and y.
stdio.write('Edit distance = ')
stdio.write(opt[0][0])
stdio.writeln()
# Recover and write an optimal alignment.
i = 0
j = 0
while i != M and j != N:
if opt[i][j] == opt[i + 1][j] + 2:
stdio.writef(x[i] + ' ' + '-' + ' ' + '2' + "\n")
i += 1
elif opt[i][j] == opt[i][j + 1] + 2:
stdio.writef('-' + ' ' + y[j] + ' ' + '2' + "\n")
j += 1
elif (x[i]) == (y[j]):
stdio.writef(x[i] + ' ' + y[j] + ' ' + '0' + "\n")
i += 1
j += 1
else:
stdio.writef(x[i] + ' ' + y[j] + ' ' + '1' + "\n")
i += 1
j += 1