1 import numpy as np 2 3 4 def update(a: int, b: int, c: int) -> tuple: 5 if a > b and a > c: 6 return a, "↖" 7 if b > a and b > c: 8 return b, "↑" 9 return c, "←" 10 11 12 def mapping(c: str) -> int: 13 if c == "A": 14 return 0 15 elif c == "C": 16 return 1 17 elif c == "G": 18 return 2 19 else: 20 return 3 21 22 23 def global_alignment(S: list, d: int, X: str, Y: str) -> tuple: 24 n, m = len(X), len(Y) 25 dp = [[0 for j in range(m + 1)] for i in range(n + 1)] 26 flag = [[" " for j in range(m + 1)] for i in range(n + 1)] 27 for j in range(m): 28 dp[0][j + 1] = dp[0][j] + d 29 flag[0][j + 1] = "←" 30 for i in range(n): 31 dp[i + 1][0] = dp[i][0] + d 32 flag[i+1][0] = "↑" 33 for i in range(1, n + 1, 1): 34 for j in range(1, m + 1, 1): 35 a = mapping(X[i - 1]) 36 b = mapping(Y[j - 1]) 37 dp[i][j], flag[i][j] = update(dp[i - 1][j - 1] + S[a][b], dp[i - 1][j] + d, dp[i][j - 1] + d) 38 return dp, flag 39 40 41 if __name__ == '__main__': 42 X = "GAGT" 43 Y = "AGACCT" 44 S = [#A C G T 45 [ 1, -3, -2, -3], # A 46 [-3, 1, -3, -2], # C 47 [-2, -3, 1, -3], # G 48 [-3, -2, -3, 1] # T 49 ] 50 dp, flag = global_alignment(S, -1, X, Y) 51 print(np.array(dp)) 52 print(np.array(flag))