This is a clean and reusable way to count nucleotides. We create a function that takes a DNA sequence, cleans it, counts the bases using Counter, and returns only the counts for A, T, G, and C.
| Code |
| from collections import Counter def count_nucleotides(dna): dna = dna.strip().upper() counts = Counter(dna) result = { “A”: counts.get(“A”, 0), “T”: counts.get(“T”, 0), “G”: counts.get(“G”, 0), “C”: counts.get(“C”, 0) } return result dna = “ATGCGCATG” print(count_nucleotides(dna)) |
| Output: {‘A’: 2, ‘T’: 2, ‘G’: 3, ‘C’: 2} |
Step-by-Step Explanation
- Import Counter
| from collections import Counter |
We import the Counter class from the collections module.
Counter is a special dictionary that automatically counts items.
- Define the Function
| def count_nucleotides(dna): |
We create a function named count_nucleotides that accepts one parameter: dna (the DNA sequence).
- Clean the DNA Sequence
| dna = dna.strip().upper() |
- .strip() → Removes any extra spaces from the beginning or end of the string.
- .upper() → Converts all letters to uppercase (so “atgc” becomes “ATGC”).
This makes the function more reliable.
- Count All Characters Using Counter
| counts = Counter(dna) |
Counter goes through the entire DNA sequence and counts every character.
For the sequence “ATGCGCATG”, it creates:
| Counter({‘G’: 3, ‘A’: 2, ‘T’: 2, ‘C’: 2}) |
- Create a Clean Result Dictionary
| result = { “A”: counts.get(“A”, 0), “T”: counts.get(“T”, 0), “G”: counts.get(“G”, 0), “C”: counts.get(“C”, 0) } |
Here we build a new dictionary that only contains A, T, G, and C.
- counts.get(“A”, 0) means:
- If “A” exists in counts, return its value.
- If “A” does not exist, return 0.
This ensures that even if a base is missing, it still appears in the result with a count of 0.
- Return the Result
| return result |
The function returns the final dictionary.
- Call the Function and Print the Output
| dna = “ATGCGCATG” print(count_nucleotides(dna)) |
We pass the DNA sequence to the function and print the returned dictionary.
Summary
This method is better because:
- It is reusable (you can call the function with any DNA sequence).
- It cleans the input (removes spaces and converts to uppercase).
- It always returns counts for A, T, G, and C.
- It uses Counter, which is fast and clean.