Jack William
Jack William

Reputation: 77

Is there a different way to count repetitions in a string except count?

I'm doing CS50 DNA problem, and the python count function keeps returning off values, and I'm not sure why. I tried using find, but my implementation was wrong

import csv, sys
#check if all arguments are provided
if len(sys.argv) != 3:
    print("Usage: python dna.py data.csv sequence.txt")
    exit()

#sets database to first argument
databaseFile = sys.argv[1]

#sequence is second file
sequenceFile = sys.argv[2]

#make list for data
data = []
database = []

#open csv file
with open(databaseFile, 'r') as csvfile:

    #make reader
    csvreader = csv.reader(csvfile)

    #read in the headers
    fields = next(csvreader)
    fields.remove("name")

    #read in the rows of data in database
    for row in csvreader:
        #add data, with names and database with just numbers
        data.append(row)
        database.append([int(i) for i in row[1:]])

#open sequence
sequence = open(sequenceFile, 'r').readline()

results = []
#for add repetitions to results
for field in fields:
    results.append(sequence.count(field))

print(results)
found = False
for i in database:
    if (results == i):
        print(data[i])
        found = True
if not found:
    print("No match")

Which other method can i use to count the repetitions of 'field' in sequence for example when i load:

python dna.py databases/large.csv sequences/19.txt I get results as: [47, 40, 34, 11, 24, 31, 60, 26] No match

instead of fred which is: [37, 40, 10, 6, 5, 10, 28, 8]

problem can be found at: https://cs50.harvard.edu/x/2020/psets/6/dna/

Upvotes: 1

Views: 231

Answers (1)

Chris Charley
Chris Charley

Reputation: 6598

Using a regular expression to find consecutive matches.

import re

s = 'AGTCAGTCAGTCTTTTAGCTAGTC'
STR = 'AGTC'

strands = re.findall(f'(?:{STR})+', s)
print(strands) # prints `['AGTCAGTCAGTC', 'AGTC']`

my_max = max(map(len, strands))//len(STR)
print(my_max)

Prints 3 which is correct as it appears 3 times consecutively (and once more at the end of the sequence).

I hope this snippet can help for this portion of your problems.

Upvotes: 2

Related Questions