CS50(2020)PSET6 DNA索引器错误:列表索引超出范围

2024-05-15 11:22:26 发布

您现在位置:Python中文网/ 问答频道 /正文

这对我来说是一个非常困难的问题,我甚至很难找到工作。此时,这就是我的代码的样子;我甚至无法判断它是否输出任何内容,因为我无法让它在没有错误的情况下运行

import csv
from cs50 import get_string
from sys import argv

if len(argv) != 3:
    print("Usage: python dna.py data.csv sequence.txt")
    exit()

# Load Dictionary into the system
with open(argv[1], 'r') as file:
    reader = csv.reader(file, delimiter=',')
    dna_data = list(reader)
    str_names = (dna_data[0][1:])

# Load Text DNA Sequence into system
text = open(argv[2], 'r')
sequence = text.read()
linecount = 0

# occurrences of each str in dna sequence
occurrences = []
for i in range(0,len(str_names)):
    start = 0
    substr_count = 0
    consecutive = 0
    while True:
        string = sequence
        substring = str(dna_data[i])
        location = string.find(substring,start)
        if location == -1:
            break
        if location != start:
            consecutive = 1
        else:
            consecutive += 1
        if consecutive > substr_count:
            substr_count = consecutive
        start = location + len(substring)
    occurrences.append(substr_count)
    substr_count = 0

repeats = []
match = 0
name = 0
for i in range (1, len(dna_data)):
    for j in range (1, len(dna_data[i])):
        repeats.append(dna_data[i][j])
    for k in range(1, len(dna_data)):
        if int(repeats[k]) == int(occurrences[k]): # THIS IS WHERE THE ERROR IS
            match += 1
            nomatch = False
        else:
            nomatch = True
    if match == len(occurrences) and nomatch == False:
        print(dna_data[i][0])
        name += 1
    else:
        nomatch = True
        match = 0
if nomatch == True and name == 0:
    print("No Match")

我相信答案可能很简单,但我就是想不出来。我非常确定“事件”和“重复”的列表长度实际上都是“len(dna_数据)”,但错误似乎表明k的增加超过了其中一个列表的长度。这里有什么明显的问题吗?如何比较重复列表和出现列表中位置k处的数字?谢谢


Tags: infordatalenifcountrangedna