Skip to content

Commit a989e80

Browse files
author
shiv
committed
Added LCIS dynamic programming code. Feels good to code after all this time
1 parent 9d18bbe commit a989e80

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

LCIS.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# SHIV's code
2+
# Longest Common Increasing Subsequence
3+
4+
# Testing arrays
5+
a1 = [3,4,9,1]
6+
a2 = [5,3,8,9,10,2,1]
7+
a3 = [50, 3, 10, 7, 40, 80]
8+
a4 = [3, 10, 2, 1, 20]
9+
a5 = "AGGTAB"
10+
a6 = "GXTXAYB"
11+
12+
# find the LIS for any list
13+
def LIS(a):
14+
if len(a) < 1: return 1
15+
least_index = 0
16+
for ind, i in reversed(list(enumerate(a))):
17+
#print(i, a[-1])
18+
if i < a[-1]:
19+
least_index=ind
20+
break
21+
return max(LIS(a[:-1]),1+LIS(a[:least_index]))
22+
23+
# This func will now find LCS
24+
# Also a very nice way to see how to retrieve the elements of the efficient elements
25+
def LCS(a, b):
26+
try:
27+
if len(a) <1: return 0, []
28+
if a[-1] == b[-1]:
29+
#cost, arr = LCS(a[:-1], b[:-1])
30+
#print(arr, a[-1], cost)
31+
cost, arr = LCS(a[:-1], b[:-1])
32+
arr.append(a[-1])
33+
return 1+cost, arr
34+
else:
35+
cost1, arr1 = LCS(a[:-1], b)
36+
cost2, arr2 = LCS(a, b[:-1])
37+
costs = [cost1, cost2]
38+
arrs = [arr1, arr2]
39+
ind = costs.index(max(costs))
40+
return costs[ind], arrs[ind]
41+
except:
42+
return 0, []
43+
44+
# This bro finally finds the LCIS
45+
def LCIS(a, b):
46+
l, x = LCS(a, b)
47+
cost = LIS(x)
48+
return cost
49+
50+
# Yayyyy!
51+
print(LCIS(a1, a2))

0 commit comments

Comments
 (0)