I need some advises how i can improve my code and make it more pythonic. Cause i feel like my code is too long.
This is my solution to cs50 DNA problem:
import sys
import csv
if len(sys.argv) != 3:
print(f"Usage: python {sys.argv[0]} database.csv sequence.txt")
sys.exit(1)
database = sys.argv[1]
sequence = sys.argv[2]
people = {}
shtares = [] # sh(ort)ta(ndem)re(peats), because str in low case is ocupied
keys = []
# Saves all STRs to "shtares",
with open(database, "r") as file:
reader = csv.reader(file)
for row in reader:
shtares = row[1:]
break
# Saves all data in dictionary "people" and all keys in "keys"
for row in reader:
people[row[0]] = [int(x) for x in row[1:]]
keys.append(row[0])
with open(sequence, "r") as file:
dna = file.read()
src = [] # Samples repeat count(src)
x = 0
# Save number of consecutively repeated STRs for each STR
for shtare in shtares:
i = 0
max_count = 0
cur_count = 0
shtare_length = len(shtare)
# Check if STR matches curent DNA part
while i <= len(dna) - shtare_length:
dna_part = dna[i:i + shtare_length]
if cur_count != 0:
if dna_part != shtare:
cur_count = 0
if dna_part == shtare:
cur_count += 1
i += shtare_length
else:
i += 1
if cur_count > max_count:
max_count = cur_count
src.append(max_count)
x += 1
# Looking for DNA sample STRs count matches to someone's in people STRS count
for x in range(len(keys)):
for y in range(len(shtares)):
if src == people[keys[x]]:
print(keys[x])
sys.exit(0)
print("No match")
Program takes as input one sequence of DNA in .txt file - for example:
AAGGTAAGTTTAGAATATAAAAGGTGAGTTAAATAGAATAGGTTAAAATTAAAGGAGATCAGATCAGATCAGATCTATCTATCTATCTATCTATCAGAAAAGAGTAAATAGTTAAAGAGTAAGATATTGAATTAATGGAAAATATTGTTGGGGAAAGGAGGGATAGAAGG
and one table in .csv file - for example:
name | AGATC | AATG | TATC |
---|---|---|---|
Alice | 2 | 8 | 3 |
Bob | 4 | 1 | 5 |
Charlie | 3 | 2 | 5 |
And also i feel like using csv.DictReader must be usefull i can't find any information how to save data from .csv file to dictionary. I thought this will do:
import sys
import csv
if len(sys.argv) != 3:
print(f"Usage: python {sys.argv[0]} database.csv sequence.txt")
sys.exit(1)
database = sys.argv[1]
sequence = sys.argv[2]
people = {}
with open(database, "r") as file:
reader = csv.DictReader(file)
for row in reader:
people[row[0]] = row[1:]
Bot id doesn't. I found out that slicing doesn't work in dictionary. So the other question is - How to properly save data from .csv file to dictionary?