interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / longest-common-subsequence / oracle.py

19 lines · 735 bytes Raw Blame History
1# Independent reference for "Longest common subsequence" (Python 3, standard library only).
2# expected.txt is this program's stdout; omc never produced it.
3def lcs(a, b):
4 t = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
5 for i in range(len(a)):
6 for j in range(len(b)):
7 t[i + 1][j + 1] = t[i][j] + 1 if a[i] == b[j] else max(t[i][j + 1], t[i + 1][j])
8 out = []
9 i, j = len(a), len(b)
10 while i > 0 and j > 0:
11 if a[i - 1] == b[j - 1]:
12 out.append(a[i - 1]); i -= 1; j -= 1
13 elif t[i - 1][j] >= t[i][j - 1]:
14 i -= 1
15 else:
16 j -= 1
17 return "".join(reversed(out))
18print(lcs("thisisatest", "testing123testing"))
19print(lcs("1234", "1224533324"))