【发布时间】:2020-09-05 02:28:20
【问题描述】:
刚刚完成 pset6 DNA,但我很困惑。在计算连续的 dna 序列时,如果我使用 for 循环遍历 dna 序列文本,我的代码将始终产生“不匹配”作为输出,但如果我将其更改为 while 循环以遍历 dna 序列它会工作。我不知道为什么。我在 while 循环部分下方注释掉了整个 for 循环部分。
任何帮助表示赞赏。
from sys import argv, exit
import csv
if len(argv) != 3:
print("Usage: python dna.py data.csv sequence.txt")
exit(1)
with open(argv[1], 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
header = row
header.pop(0)
break
dictionary = {}
for item in header:
dictionary[item] = 0
with open(argv[2], 'r') as dna_txt:
dna_reader = dna_txt.read()
# This iteration using while loop works
for key in dictionary:
temp = 0
max_count = 0
i = 0
# This while loop works
while i < len(dna_reader):
if dna_reader[i : i + len(key)] == key:
temp += 1
if ((i + len(key)) < len(dna_reader)):
i += len(key)
continue
else:
if temp > max_count:
max_count = temp
temp = 0
i += 1
dictionary[key] = max_count
# This iteration does not work, only difference is for loop instead of while loop, why is that? Commented out so it doesn't interfere
'''for key in dictionary:
temp = 0
max_count = 0
# This for loop does not work
for i in range(len(dna_reader)):
if dna_reader[i : i + len(key)] == key:
temp += 1
if ((i + len(key)) < len(dna_reader)):
i += len(key)
continue
else:
if temp > max_count:
max_count = temp
temp = 0
dictionary[key] = max_count'''
with open(argv[1], 'r') as file:
table = csv.DictReader(file)
for person in table:
count = 0
for dna in dictionary:
if int(dictionary[dna]) == int(person[dna]):
count += 1
else:
count = 0
if count == len(header):
print(person['name'])
exit(1)
print('No match')
exit(0)
【问题讨论】:
-
欢迎来到stackoverflow,请阅读本文以了解如何提出好问题,以便我们为您提供帮助stackoverflow.com/help/how-to-ask