【发布时间】:2022-01-14 16:29:31
【问题描述】:
我在以下部分遇到问题:# 查找 DNA 序列中每个 STR 的最长匹配项。
我不明白为什么当我 print(longest_str) 我得到的所有值都等于 0 {'AGATC': 0, 'AATG': 0, 'TATC': 0}
我是不是调用longest_match函数错了?
PD:我是编程和 python 新手,感谢您的帮助!!
import csv
import sys
def main():
# TODO: Check for command-line usage
longest_str = {}
if len(sys.argv) != 3:
sys.exit("Usage: python dna.py, data.csv, sequence.txt")
# TODO: Read database file into a variable
with open(sys.argv[1]) as f:
data = csv.DictReader(f)
# TODO: Read DNA sequence file into a variable
with open(sys.argv[2]) as f2:
dna_sequence = csv.DictReader(f2)
# TODO: Find longest match of each STR in DNA sequence
subsequences = data.fieldnames[1:]
for subsequence in subsequences:
longest_str[subsequence] = longest_match(str(dna_sequence), subsequence)
print(longest_str)
# TODO: Check database for matching profiles
return
def longest_match(sequence, subsequence):
"""Returns length of longest run of subsequence in sequence."""
# Initialize variables
longest_run = 0
subsequence_length = len(subsequence)
sequence_length = len(sequence)
# Check each character in sequence for most consecutive runs of subsequence
for i in range(sequence_length):
# Initialize count of consecutive runs
count = 0
# Check for a subsequence match in a "substring" (a subset of characters) within sequence
# If a match, move substring to next potential match in sequence
# Continue moving substring and checking for matches until out of consecutive matches
while True:
# Adjust substring start and end
start = i + count * subsequence_length
end = start + subsequence_length
# If there is a match in the substring
if sequence[start:end] == subsequence:
count += 1
# If there is no match in the substring
else:
break
# Update most consecutive matches found
longest_run = max(longest_run, count)
# After checking for runs at each character in seqeuence, return longest run found
return longest_run
main()
【问题讨论】:
-
为您提供
longest_match()的函数定义。不确定是否需要发布(也许对于不熟悉 CS50 psets 和实验室的人来说)。此外,代码格式不正确。我试图修复。您应该检查以确保所有缩进都是正确的。
标签: python arrays function variables cs50