Skip to content

Instantly share code, notes, and snippets.

@jacksmith15
Created March 31, 2020 08:26
Show Gist options
  • Save jacksmith15/73a19290c40ac0a60fae34dc2c602e3b to your computer and use it in GitHub Desktop.
Save jacksmith15/73a19290c40ac0a60fae34dc2c602e3b to your computer and use it in GitHub Desktop.
from sys import argv, exit
import csv
def main():
if len(argv) != 3:
print("Usage: python dna.py filename.csv filename.txt")
exit(1)
people = []
# The with syntax ensures the file is closed!
# read csv into memory, populating array of persons
with open(argv[1], 'r') as table:
reader = csv.DictReader(table)
# read dna file into vaiable
with open(argv[2], 'r') as txt:
text = file.read()
reader = csv.DictReader(table)
dna_words = (reader.fieldnames)
num_terms = len(dna_words)
Row = namedtuple("Row", dna_words)
people = [
Row(**row)
for row in reader
]
# make function to search for how many repeating occurances of that string there are in the text
def max_consecutive(string):
maximum = 0
length = len(string)
for j in range(len(text)):
counter = 0
while text[j:(j + length)] == string:
counter += 1
j = j + length
if maximum < counter:
maximum = counter
return maximum
# create person structure by placing the names of str strings into max_consecutive function
# Row(**{"short": "riff", "lover": "boy"}) is the same as Row(short="riff", lover="boy")
sample = Row(
**{dna_word: max_consecutive(dna_word) for dna_word in dna_words}
)
# compare sample person information to the information taken from CSV file to determine whether the DNA matches anyone
# I think this is easier to read as a list comprehension - it has the benefit of being one statement
matches = [
person
for person in people
if person == sample # If the values are the same then the objects are equal
]
if matches:
print(matches[0])
print("No match")
exit(1) # Not sure if you want this but nice to return a different return
if __name_ == "__main__":
# This means the script only runs if called directly, as opposed to being imported.
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment