-1

This is my first coding class and I'm having trouble getting the counter to increase every time one of the given appears in the DNA sequence.

My code so far:

agat_Counter = 0
aatg_Counter= 0
tatc_Counter= 0
DNAsample = open('DNA SEQUENCE FILE.txt', 'r');
for lines in DNAsample:
    if lines in DNAsample=='AGAT':
        agat_Counter+=1
    else:
        agat_Counter+=0
print(agat_Counter)
    
for lines in DNAsample:
    if lines in DNAsample=='AATG':
        aatg_Counter+=1
    else:
        aatg_Counter+=0
print(aatg_Counter)
for lines in DNAsample:
    if lines in DNAsample=='TATC':
        tatc_Counter+=0
    else:
        tatc_Counter+=0
print(tatc_Counter)

2 Answers2

1

You can do this with many ways. One of the more simple is the following:

DNAsample = open('DNA SEQUENCE FILE.txt', 'r').read()
agat_Counter = DNAsample.count('AGAT')
aatg_Counter= DNAsample.count('AATG')
tatc_Counter= DNAsample.count('TATC')
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30
0

This should work. The issue is with your if statements. as well as once you iterate through the file once, the file pointer is at the end (I think) so it won't go back through. The code below iterates through each line one at a time and compares the string to the 4 character sequence, note that the .strip() removes the trailing \n and or \r characters that are in the line variable as the file is iterated through.

In general, when opening files it is best to use with open(filename, mode) as var: as shown below this handles closing the file once it is done and elminates the risk of un-closed file handles.

Assumption based on original code is that the DNA SEQUENCE FILE.txt file is organized as such:

AGAT
AATG
...
agat_Counter = 0
aatg_Counter= 0
tatc_Counter= 0

with open('DNA SEQUENCE FILE.txt', 'r') as DNAample:
    for line in DNAsample:
        strippedLine = line.strip()
        if strippedLine == 'AGAT':
            agat_Counter += 1
        elif strippedLine == 'AATG':
            aatg_Counter += 1   
        elif stripepdLine == 'TATC':
            tatc_Counter += 1

print(agat_Counter)
print(aatg_Counter)
print(tatc_Counter)
Tom Myddeltyn
  • 1,307
  • 1
  • 13
  • 27