0

tl;dr: Code seems to run perfectly, check50/Submit50, however, is timing out before a response is provided.

I have manually checked all test cases provided on the Pset page: small.csv 1.txt through to large.csv 21.txt and I get the correct answer. It just seems to be an efficiency issue.

I've stripped it down as best I can, but check50 keeps timing out.

from sys import argv, exit
import sys
import csv


# checks for 2 command lines exactly
if len(argv) < 3:
    print("Usage: python dna.py data.csv sequence.txt")
    exit(0)

# open csv file as a list
csv_file = open(sys.argv[1], newline='')
csvreader = csv.reader(csv_file)
row1 = next(csvreader)


txt_file = open(sys.argv[2], "r")
seqreader = txt_file.read()

#print(seqreader)

# Create empty list
counter = []

# Iterate through DNA
for i in range(1, len(row1)):
    occurance = 0
    n = 1

    while row1[i]*n in seqreader:
        n += 1
    if (n - 1) > occurance:
        occurance = n - 1
    counter.append(occurance)
    #print(occurance)

counterlen = len(counter)

# Check if no match
match = False
for row in csvreader:
    for c in range(counterlen):

        # row itteration
        if int(row[c+1]) != int(counter[c]):
            break
        else:
            print(row[0])
            match = True
            break

# if no match
if match == False:
    print("No match")

txt_file.close()
csv_file.close()

Any suggestions?

EDIT: After some tinkering, it seems like I am doing unnecessary iterations, still at a loss as to how I can prevent this...

0

This for c in seqreader: will iterate once for every letter in the txt file. That is over 6700 times for 18.txt! And program doesn't use c in that loop. That looks like the problem.

NB If you edit the question, select the code and click the {} icon in the format bar, it will format the code so it is legible.

--AFTER COMMENT-- This line elif c == (counterlen)-1: in the original code was changed to this else: in the current code, and that makes all the difference.

  • Thanks for pointing that out, I have updated my code above. However instead of only receiving one value, now I get 2 or 3 names printed. For example: 19.txt - expected: Fred Actual: Fred Ginny Ron Some of the others like 20 still provide the correct output. – Depricated1 Feb 4 '20 at 6:55
  • The "new" code also has a (significant) difference in the # Check if no match block – DinoCoderSaurus Feb 4 '20 at 14:42
  • Sorry, not sure I follow. – Depricated1 Feb 5 '20 at 8:06
  • specifics added to answer – DinoCoderSaurus Feb 5 '20 at 14:09
  • Thank you so much! Feel like such an idiot XD – Depricated1 Feb 5 '20 at 15:23

You must log in to answer this question.

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