[Python | Rosalind | defaultdict] Counting DNA Nucleotides

##########################
# Counting DNA Nucleotides
##########################
# 1) defaultdict instead of dict
from collections import defaultdict
with open('rosalind_dna.txt', 'r') as myFile:
    letters = myFile.read().strip()
# note the requirement for argument such as int / list in defaultdict
# defaultdict will throw an int 0 for key get called but not existent
# dict will throw an error for nonexistent key once called
counts = defaultdict(int)
for letter in letters:
    counts[letter] += 1
print(counts['A'], counts['C'], counts['G'], counts['T'])

# 2) count method
with open('rosalind_dna.txt', 'r') as myFile:
    letters = myFile.read()
print(letters.count("A"), letters.count("C"), letters.count("G"), letters.count("T"))

# 3) for-loop
with open('rosalind_dna.txt', 'r') as myFile:
    letters = myFile.read()
countA = 0
countT = 0
countG = 0
countC = 0
for letter in letters:
    if letter == "A":
        countA += 1
    elif letter == "T":
        countT += 1
    elif letter == "G":
        countG += 1
    elif letter == "C":
        countC += 1
print(countA, countC, countG, countT)

你可能感兴趣的:([Python | Rosalind | defaultdict] Counting DNA Nucleotides)