Antique Tall Case / Grandfather Clock Disassembly tutorial: https://www.youtube.com/watch?v=DpZWsx7qDFc
2. http://rosalind.info 有幾題相當困難,還在思考怎麼做。
def longest_common_subsequence(s, t):
c, b = longest_common_subsequence_table(s, t)
return longest_common_subsequence_printable(b, s, len(s), len(t))
def longest_common_subsequence_table(s, t):
m, n = len(s), len(t)
b = [[0 for _ in range(n)] for _ in range(m)]
c = [[0 for _ in range(n+1)] for _ in range(m+1)]
for i in range(m):
for j in range(n):
if s[i] == t[j]:
c[i+1][j+1] = c[i][j] + 1
b[i][j] = 'Diagonal'
elif c[i][j+1] > c[i+1][j]:
c[i+1][j+1] = c[i][j+1]
b[i][j] = 'Up'
else:
c[i+1][j+1] = c[i+1][j]
b[i][j] = 'Left'
return c, b
def longest_common_subsequence_printable(b, s, i, j):
reversed_lcs = ''
while True:
if i == 0 or j == 0:
break
direction = b[i-1][j-1]
if direction == 'Diagonal':
lcs += s[i-1]
i, j = i-1, j-1
elif direction == 'Up':
i, j = i-1, j
else:
i, j = i, j-1
return reversed_lcs[::-1]
def LIS(sequence):
# Time complexity is O(n^2)
lis_len = [1] * len(sequence)
for i in range(len(sequence)):
for j in range(i+1, len(sequence)):
if sequence[i] < sequence[j]:
lis_len[j] = max(lis_len[j], lis_len[i] + 1)
rv = []
curr_len = max(lis_len)
for i in range(len(sequence) - 1, -1, -1):
if curr_len == lis_len[i]:
rv.append(sequence[i])
curr_len -= 1
return rv[::-1]
def LIS(sequence):
# Robinson-Schensted-Knuth Algorithm
# Time complexity is O(n log(n))
if not sequence:
return []
aux_len = [1]
aux_rv = [sequence[0]]
for i in range(1, len(sequence)):
x = sequence[i]
if x > aux_rv[-1]:
aux_rv.append(x)
aux_len.append(len(aux_rv))
else:
j = bisect.bisect_right(aux_rv, x)
aux_rv[j] = x
aux_len.append(j + 1)
rv = []
curr_len = len(aux_rv)
for i in range(len(sequence) - 1, -1, -1):
if curr_len == aux_len[i]:
rv.append(sequence[i])
curr_len -= 1
return rv[::-1]
這個時間複雜度是 O(n log(n)),關鍵就是用 binary search 把時間複雜度從 n 降成 log(n)。
use strict;
use warnings;
while (my $dna = <>) {
chomp $dna;
my @symbols = split //, $dna;
my %count = (
'A' => 0,
'C' => 0,
'G' => 0,
'T' => 0,
);
for my $symbol (@symbols) {
$count{$symbol}++;
}
print $count{'A'} . ' ' ,
$count{'C'} . ' ' ,
$count{'G'} . ' ' ,
$count{'T'} . "\n";
}
實際寫頗土炮。import sys
dna = sys.stdin.read().strip()
print(' '.join([str(dna.count(i)) for i in 'ACGT']))
不得不說演化過的 Python 習得各家語言的優點,才能淬鍊精幹短小的程式碼。dna = STDIN.read.chomp
puts [dna.count('A'), dna.count('C'), dna.count('G'), dna.count('T')].join ' '
短短的蠻可愛的