-
Notifications
You must be signed in to change notification settings - Fork 0
/
lgis.py
65 lines (47 loc) · 1.92 KB
/
lgis.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def test_longest_increasing_subsequence1():
sequence = [5, 1, 4, 2, 3]
expected = [1, 2, 3]
actual = longest_increasing_subsequence(sequence)
assert actual == expected
def test_longest_increasing_subsequence2():
sequence = [8, 2, 1, 6, 5, 7, 4, 3, 9]
expected = [2, 6, 7, 9]
actual = longest_increasing_subsequence(sequence)
assert actual == expected
def test_longest_increasing_subsequence3():
sequence = [1, 3, 6, 7, 9, 4, 10, 5, 6]
expected = [1, 3, 6, 7, 9, 10]
actual = longest_increasing_subsequence(sequence)
assert actual == expected
def test_longest_decreasing_subsequence1():
sequence = [5, 1, 4, 2, 3]
expected = [5, 4, 3]
actual = longest_decreasing_subsequence(sequence)
assert actual == expected
def test_longest_decreasing_subsequence2():
sequence = [8, 2, 1, 6, 5, 7, 4, 3, 9]
expected = [8, 6, 5, 4, 3]
actual = longest_decreasing_subsequence(sequence)
assert actual == expected
def parse(file):
n = int(file.readline().strip())
return [int(n) for n in file.readline().strip().split()]
def longest_increasing_subsequence(sequence: list[int]) -> list[int]:
subsequences = [[] for _ in range(len(sequence))]
for i in range(len(sequence)):
subs = [
sub for j, sub in enumerate(subsequences[:i]) if sequence[j] < sequence[i]
]
subsequences[i] = max(subs, key=len, default=[]) + [sequence[i]]
return max(subsequences, key=len, default=[])
def longest_decreasing_subsequence(sequence):
return longest_increasing_subsequence(sequence[::-1])[::-1]
def main():
with open("rosalind_lgis.txt") as file:
sequence = parse(file)
increasing = longest_increasing_subsequence(sequence)
print(" ".join(str(n) for n in increasing))
decreasing = longest_decreasing_subsequence(sequence)
print(" ".join(str(n) for n in decreasing))
if __name__ == "__main__":
main()