Last active
November 18, 2021 00:31
-
-
Save zedchance/e627a0138fc175ab7015b14f3492f656 to your computer and use it in GitHub Desktop.
Longest common subsequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# longest common subsequence | |
def lcs(x, y): | |
""" returns longest common sequence length, exponential runtime complexity """ | |
if len(x) == 0 or len(y) == 0: | |
return 0 | |
elif x[-1] == y[-1]: | |
return lcs(x[:-1], y[:-1]) + 1 | |
else: | |
return max(lcs(x[:-1], y), | |
lcs(x, y[:-1])) | |
def print_c(c): | |
for row in c: | |
for col in row: | |
print(f'{col:2}', end=" ") | |
print() | |
print() | |
def dynamic_lcs(x, y): | |
""" returns longest common sequence length, linear runtime complexity """ | |
m = len(x) + 1 | |
n = len(y) + 1 | |
c = [[-1 for i in range(n)] for j in range(m)] | |
b = [[0 for i in range(n)] for j in range(m)] | |
# base cases | |
for i in range(m): | |
c[i][0] = 0 | |
for j in range(n): | |
c[0][j] = 0 | |
# compute sub problems | |
for i in range(1, m): | |
for j in range(1, n): | |
if x[i - 1] == y[j - 1]: | |
c[i][j] = c[i - 1][j - 1] + 1 | |
b[i][j] = 1 # up-left arrow | |
else: | |
if c[i - 1][j] >= c[i][j - 1]: | |
c[i][j] = c[i - 1][j] | |
b[i][j] = 2 # up arrow | |
else: | |
c[i][j] = c[i][j - 1] | |
b[i][j] = 3 # left arrow | |
def _print_lcs(i, j): | |
if i == 0 or j == 0: | |
return | |
if b[i][j] == 1: # up-left arrow | |
_print_lcs(i - 1, j - 1) | |
print(x[i - 1], end=" ") | |
elif b[i][j] == 2: # up arrow | |
_print_lcs(i - 1, j) | |
else: # left arrow | |
_print_lcs(i, j - 1) | |
print_c(c) | |
_print_lcs(len(x), len(y)) | |
if __name__ == '__main__': | |
x = ['a', 'b', 'c', 'b', 'd', 'a', 'b'] | |
y = ['b', 'd', 'c', 'a', 'b', 'a'] | |
# print(lcs(x, y)) | |
dynamic_lcs(x, y) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#lang racket | |
(define (lcs xs ys) | |
(cond ((or (empty? xs) (empty? ys)) 0) | |
((equal? (first xs) (first ys)) (+ (lcs (rest xs) (rest ys)) 1)) | |
(else (max (lcs (rest xs) ys) | |
(lcs ys (rest xs)))))) | |
(lcs '("a" "b" "c" "b" "d" "a" "b") | |
'("b" "d" "c" "a" "b")) |
Author
zedchance
commented
Nov 17, 2021
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment