I am trying to improve my code for pset6, it works but currently takes a few minutes for the larges files. Can I get some help as to how to improve performance?

from sys import argv, exit
import csv
import sys

# Check if only two arguments
if len(argv) != 3:
    print("Need two files")

# Read database of DNA STR and save STR names
dnatable = csv.DictReader(open(argv[1]))
STR = dnatable.fieldnames
ncol = len(STR)
STRM = []

# read the sequence to analyze
with open(argv[2], 'r') as file:
    data = file.read().replace('\n', '')

# iterate to find if there is a match
for p in range (ncol):  #iterate number of columnes in small or large dictionary - ncol
    l = len(STR[p])   # l is distance from first letter to last letter
    k = 0
    maxc = 0
    l2 = len(data)
    for k in range(l2):  #iterate over every starting position in the file
        counter = 0
        i = 0
        r = 0
        while i < l2:  #iterate over every letter starting in k and match with STR(THIS IS WHERE I NEED HELP)
            if STR[p] == data[i+k:j+k]:
                counter = counter + 1
                i += l 
                if counter > maxc:
                    maxc = counter
                i += 1
                counter = 0
    print (STRM)

dnatable2 = csv.reader(open(argv[1]))
i = 0 
for row in dnatable2:
    j = 0
    tracker = True
    for col in row:
        if (int(row[j])- int(STRM[j])) != 0:
            tracker = False 
        j = j + 1
    i = i + 1    
    if tracker == True:

if tracker == False: 
    print ("No match")

k = 1
dnatable3 = csv.reader(open(argv[1]))

for row in dnatable3:
    if k == i:
        Winner = (row[0])
    k = k + 1

print (Winner)

2 Answers 2


Nested loops takes lots of time to execute, you can try to redesign your code to that will make you no use too much nested loops..


Thank I think I figuted it out basically through using re.find functions and re-writing the whole thing to focus how many times the sequenence repeates iteself without going through the whole code

You must log in to answer this question.

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