Im struggling with the PSET6 DNA solution. So far I have opened the dna file and converted it into a dictionary as well as reading the text file. I'm trying to count the consecutive times an STR occurs in the text file but my code does not seem to work. In my code as per below I've tried to execute:

For each key in the newly established dictionary which corresponds to a STR and for each character in the text file if the ith character plus the length of the key is equal to the key while the next sequence is the same as the one before then increment a temp counter and if the temp counter is greater than the max_count then replace the max_count with the temp variable. Would appreciate any tips or suggestions with my code below! Thanks!

from sys import argv
import csv

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

with open(argv[1], "r") as dna_file:
     dna_list = csv.reader(dna_file)

for row in dna_list:
    dna_samples = row

dna_dict = {}

for item in dna_samples:
    dna_dict[item] = 0


with open(argv[2], "r") as f:
    text_data = f.read()

for key in dna_dict:
   l = len(key)
   for i in range(0, len(text_data)):
     if text_data[i:l] == key:
         temp = 0
         max_count = 0
         while text_data[i: i + l] == text_data[i - l: i]:
            temp += 1
            i += l
            if temp > max_count:
                max_count = temp

  • hey, did you figure this out? I have used a similar logic but can not seem to make this work Commented May 17, 2020 at 15:51
  • Hi, yep I got it working in the end. Two problems I had with my code. 1) i didn't reset temp to 0 at the end to ensure there is no miscount. 2) Also you might want to add 1 initially to miscount to count for the first one in sentence. Hope this helps.
    – auron98
    Commented May 19, 2020 at 8:27

1 Answer 1


I don't think that code works. It marks as a match the next position to a positive streak even when it is not. Also the for loop iterates over positions that already have been covered by the while loop (so the program ends up iterating the list multiple times). It is better to iterate through the text in reverse using while loop with just one if statement. Another method is to create a list of matches using startswith and then use an algorithm to find the consecutive matches.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .