1 回答

TA贡献1719条经验 获得超6个赞
此类问题的递归使用大量堆栈,并且比使用需要线性时间和恒定空间的内置数据结构慢得多。我知道需要递归,因为那是你的问题,但我仍然觉得我应该这么说。
这是一个递归解决方案:
首先是一个检查有效对的函数:
def valid_pair(c1, c2):
pairs = {
'G': 'C',
'C': 'G',
'A': 'T',
'T': 'A'
}
return pairs[c1] == c2
现在递归方法:
def compare_strands(s1, s2, count=0, result=["", ""]):
if not s1 or not s2: # base case
return count, result
# If it is not a valid pair
if not valid_pair(s1[0], s2[0]):
old_max, old_str = count, result
new_max, new_str = compare_strands(s1[1:], s2[1:], 0, ["", ""])
if new_max < old_max:
new_max = old_max
new_str = old_str
else:
temp_result = []
temp_result.append(result[0] + s1[0])
temp_result.append(result[1] + s2[0])
# result[1] += s2[0]
count = count + 1
new_max, new_str = compare_strands(s1[1:], s2[1:], count, temp_result)
return new_max, new_str
测试:
with open('dna.txt', 'r') as f:
size = int(f.readline())
for i in range(size):
strand1 = f.readline().strip('\n')
strand2 = f.readline().strip('\n')
print(compare_strands(strand1, strand2))
输出:
(3, ['AGC', 'TCG'])
(0, ['', ''])
(4, ['GGAC', 'CCTG'])
编辑:写入文件。
with open('dna.txt', 'r') as f:
size = int(f.readline())
for i in range(size):
strand1 = f.readline().strip('\n')
strand2 = f.readline().strip('\n')
result = compare_strands(strand1, strand2)
with open('result.txt', 'a') as result_file:
result_file.write('DNA sequece pair {}:\n'.format(i))
if result[0]:
result_file.write('{}\n{}\n\n'.format(result[1][0], result[1][1]))
else:
result_file.write('No matches found\n\n')
添加回答
举报