0

I am working on one of the TODOs where the longest match of each short tandem repeat (STR) needs to be found from the DNA sequence read—written as just "sequence" in this code. To check whether I was on the right track, I printed out the dictionary called "repeats" into which the information about the frequency of STR repeats and specific subsequences was meant to be stored. As shown in the photo, the code does not seem to single out the highlighted line, but rather, prints out the entire repeats. Could anyone tell me how to correct this code to prune out all the rest of the repeated information? i.e {'AGATC':0}, {'AGATC': 0, 'TTTTTTCT': 0} and so on.

import csv
import sys

def main():

# TODO: Check for command-line usage
    filename = sys.argv[1]
    text_file = sys.argv[2]

    if len(sys.argv) != 3:
        print("ERROR")
        sys.exit("Usage: python dna.py FILENAME")

    # TODO: Read database file into a variable
    # Reading the database contents into the "nucleotides" list.
    nucleotides = []
    with open(filename,"r") as file:
        reader = list(csv.DictReader(file))
        for row in reader:
            # Append the STR information indicated in the header of a csv file.
            # Each row read from the csv file will be returned as a list of strings
            nucleotides.append(row)

            # Read the DNA sequence file into a variable
            # Since the sequence.txt file contains only one line of code, an entire file could be read
            repeats = {}

            with open(text_file,"r") as file:
                 sequence = file.read()
                 file.close()

            # Find the longest match of each STR in the DNA sequence read
            # The function, keys(), will be used to return the headers of the "nucleotides" as a list.
            str_sequence = list(nucleotides[0].keys())[1:]
            for subsequence in str_sequence:
                repeats[subsequence] = longest_match(sequence, subsequence)

enter image description here

1
  • Your code wasn't formatted properly. I fixed -- please review to confirm it's correct. Where is this output coming from? There aren't any print statements.
    – kcw78
    Commented Feb 7, 2023 at 22:45

1 Answer 1

0

My first observations. I'm surprised this works at all. You are using file as the variable/object name in 2 places:

with open(filename,"r") as file:
     reader = list(csv.DictReader(file))  

AND:

with open(text_file,"r") as file:
     sequence = file.read()
     file.close() ## delete, not needed

The 2nd with/as is inside the 1st one. I'm surprised the 1st object isn't overwritten by the 2nd one.

Second observation: you don't need a close() statement in the with/as: block. The context manager does that for you. (Not an error, but not good code either.) :-)

You must log in to answer this question.

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