just finished pset6 DNA but I am confused. When counting the consecutive dna sequences, if I used a for loop to iterate through the dna sequence text, my code would always produce 'No Match' as the output, but if I change it too a while loop to iterate through the dna sequence it would work. I can't figure out why. I commented out the entire for loop section below the while loop section.
Any help appreciated.
from sys import argv, exit
import csv
if len(argv) != 3:
print("Usage: python dna.py data.csv sequence.txt")
exit(1)
with open(argv[1], 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for row in csv_reader:
header = row
header.pop(0)
break
dictionary = {}
for item in header:
dictionary[item] = 0
with open(argv[2], 'r') as dna_txt:
dna_reader = dna_txt.read()
# This iteration using while loop works
for key in dictionary:
temp = 0
max_count = 0
i = 0
# This while loop works
while i < len(dna_reader):
if dna_reader[i : i + len(key)] == key:
temp += 1
if ((i + len(key)) < len(dna_reader)):
i += len(key)
continue
else:
if temp > max_count:
max_count = temp
temp = 0
i += 1
dictionary[key] = max_count
# This iteration does not work, only difference is for loop instead of while loop, why is that? Commented out so it doesn't interfere
'''for key in dictionary:
temp = 0
max_count = 0
# This for loop does not work
for i in range(len(dna_reader)):
if dna_reader[i : i + len(key)] == key:
temp += 1
if ((i + len(key)) < len(dna_reader)):
i += len(key)
continue
else:
if temp > max_count:
max_count = temp
temp = 0
dictionary[key] = max_count'''
with open(argv[1], 'r') as file:
table = csv.DictReader(file)
for person in table:
count = 0
for dna in dictionary:
if int(dictionary[dna]) == int(person[dna]):
count += 1
else:
count = 0
if count == len(header):
print(person['name'])
exit(1)
print('No match')
exit(0)
The only substantial difference I can see is the effect of i += len(key)
. In a for loop, the i
variable will be re-instantiated on the start of every loop. Therefore, this statement serves no practical effect. In case of the while loop, the same i
variable is reused.
Consider this example:
for i in range(10):
print(i)
if i == 5:
i += 2
The output of this will be:
0
1
2
3
4
5
6
7
8
9
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.